java生成一个可以下载的word文件

news/2025/3/29 7:20:59/

在 Java 里,你能够借助 Apache POI 库来生成 Word 文件,并且实现文件下载功能。下面为你详细介绍实现步骤和示例代码。

1. 添加依赖

若使用 Maven 项目,需在 pom.xml 里添加 Apache POI 的依赖:

<dependencies><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.3</version></dependency>
</dependencies>

2. 生成 Word 文件

下面是一个简单的 Java 示例,用于生成包含文本内容的 Word 文件:

java">word">import org.apache.poi.xwpf.usermodel.*;word">import java.io.FileOutputStream;
word">import java.io.IOException;word">public word">class WordGenerator {word">public word">static word">void generateWord(String filePath) {// 创建一个新的 Word 文档对象XWPFDocument document = word">new XWPFDocument();// 创建一个段落对象XWPFParagraph paragraph = document.createParagraph();// 创建一个文本运行对象,用于添加文本内容XWPFRun run = paragraph.createRun();run.setText("这是一个使用 Java 生成的 Word 文件示例。");word">try (FileOutputStream out = word">new FileOutputStream(filePath)) {// 将文档写入输出流document.write(out);System.out.println("Word 文件生成成功!");} word">catch (IOException e) {e.printStackTrace();}}word">public word">static word">void main(String[] args) {// 指定生成的 Word 文件的路径String filePath = "example.docx";generateWord(filePath);}
}

3. 实现文件下载功能(基于 Spring Boot)

若要在 Web 应用中实现文件下载功能,可借助 Spring Boot 来达成。下面是一个简单的 Spring Boot 控制器示例:

java">word">package com.example.sc.user.controller;word">import org.apache.poi.xwpf.usermodel.*;
word">import org.springframework.http.HttpHeaders;
word">import org.springframework.http.HttpStatus;
word">import org.springframework.http.MediaType;
word">import org.springframework.http.ResponseEntity;
word">import org.springframework.web.bind.annotation.GetMapping;
word">import org.springframework.web.bind.annotation.RequestMapping;
word">import org.springframework.web.bind.annotation.RestController;word">import java.io.ByteArrayOutputStream;
word">import java.io.IOException;@RestController
@RequestMapping("/download")
word">public word">class WordDownloadController {@GetMapping("/word")word">public ResponseEntity<word">byte[]> downloadWord() {// 创建一个新的 Word 文档对象XWPFDocument document = word">new XWPFDocument();// 创建一个段落对象XWPFParagraph paragraph = document.createParagraph();// 创建一个文本运行对象,用于添加文本内容XWPFRun run = paragraph.createRun();run.setText("这是一个可以下载的 Word 文件示例。");run.setText("这是一个可以下载的 Word 文件示例。");run.setText("这是一个可以下载的 Word 文件示例。");run.setText("这是一个可以下载的 Word 文件示例。");run.setText("这是一个可以下载的 Word 文件示例。");run.setText("这是一个可以下载的 Word 文件示例。");run.setText("这是一个可以下载的 Word 文件示例。");word">try (ByteArrayOutputStream out = word">new ByteArrayOutputStream()) {// 将文档写入输出流document.write(out);word">byte[] bytes = out.toByteArray();// 设置响应头HttpHeaders headers = word">new HttpHeaders();headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);headers.setContentDispositionFormData("attachment", "example.docx");// 返回响应实体word">return word">new ResponseEntity<>(bytes, headers, HttpStatus.OK);} word">catch (IOException e) {e.printStackTrace();word">return word">new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);}}@GetMapping("/poem")word">public ResponseEntity<word">byte[]> downloadPoemWord() {// 创建一个新的 Word 文档对象XWPFDocument document = word">new XWPFDocument();// 诗名String poemTitle = "静夜思";// 诗的内容String[] poemLines = {"床前明月光,","疑是地上霜。","举头望明月,","低头思故乡。"};// 设置诗名格式XWPFParagraph titleParagraph = document.createParagraph();titleParagraph.setAlignment(ParagraphAlignment.CENTER);XWPFRun titleRun = titleParagraph.createRun();titleRun.setText(poemTitle);titleRun.setFontSize(24);titleRun.setFontFamily("微软雅黑");// 为诗的每一行设置格式word">for (String line : poemLines) {XWPFParagraph lineParagraph = document.createParagraph();lineParagraph.setAlignment(ParagraphAlignment.CENTER);XWPFRun lineRun = lineParagraph.createRun();lineRun.setText(line);lineRun.setFontSize(18);lineRun.setFontFamily("微软雅黑");lineRun.setItalic(true);lineRun.setUnderline(UnderlinePatterns.SINGLE);}word">try (ByteArrayOutputStream out = word">new ByteArrayOutputStream()) {// 将文档写入输出流document.write(out);word">byte[] bytes = out.toByteArray();// 设置响应头HttpHeaders headers = word">new HttpHeaders();headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);headers.setContentDispositionFormData("attachment", "poem.docx");// 返回响应实体word">return word">new ResponseEntity<>(bytes, headers, HttpStatus.OK);} word">catch (IOException e) {e.printStackTrace();word">return word">new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);}}
}

4. 运行 Spring Boot 应用

创建一个 Spring Boot 主应用类,然后运行该应用:

java">word">import org.springframework.boot.SpringApplication;
word">import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
word">public word">class YourApplication {word">public word">static word">void main(String[] args) {SpringApplication.run(YourApplication.word">class, args);}
}

5. 测试文件下载

启动 Spring Boot 应用后,在浏览器中访问 http://localhost:8080/download/word,浏览器会自动下载生成的 Word 文件。

总结

  • 运用 Apache POI 库能够方便地生成 Word 文件。
  • 在 Spring Boot 应用中,可借助 ResponseEntity 实现文件下载功能。
文章来源:https://blog.csdn.net/qq_45089709/article/details/146354222
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ppmy.cn/news/1580920.html

相关文章

【Qt】信号signal是单向的

在 Qt 中&#xff0c;信号&#xff08;Signal&#xff09; 是单向的&#xff0c;这意味着信号只能从发送者&#xff08;发出信号的对象&#xff09;传递到接收者&#xff08;连接到信号的槽函数或另一个信号&#xff09;&#xff0c;而不能反向传递数据或信息。 信号的基本特性…

深入理解 RLP 编码与 JSON:原理、应用与比较

在区块链和数据存储领域&#xff0c;RLP&#xff08;Recursive Length Prefix&#xff09;编码和**JSON&#xff08;JavaScript Object Notation&#xff09;**是两种重要的数据编码方式。它们分别适用于不同的应用场景&#xff0c;并具有不同的优缺点。本文将系统性地分析 RLP…

知识库--Milvus

引言&#xff1a; 本教程由以下两部分构成&#xff1a; 代码示例&#xff1a;通过实际构建Milvus知识库的代码演示&#xff0c;提供 hands-on 的操作体验。 代码解析&#xff1a;详细解释代码的每一部分&#xff0c;帮助读者深入理解Milvus的工作原理和实现细节。 通过这两…

Milvus vs. ElasticSearch:向量库检索性能测试

目录 1. 构建检索库2. 测试条件3. 测试结果4. 性能分析5. 结论 1. 构建检索库 构建通用场景库总计约2万张。构建车辆数据库总计约12万张。构建公共数据库&#xff0c;包括Flickr30k、COCO、nlvr2、vqa等数据集约43万张。 2. 测试条件 环境说明&#xff1a;分别单机部署Milvu…

深兰科技获评“产学研用——共研体联盟”链主型企业称号

3月18日下午&#xff0c;浦东新区工商联举办“金融服务助发展、法护民企促壮大”主题活动。活动期间&#xff0c;产学研用共研体联盟正式成立&#xff0c;深兰科技凭在人工智能产学研用方面所做出的创新和成绩&#xff0c;获评“产学研用--共研体联盟”链主型企业称号。 此次授…

【NLP】 API在大语言模型中的应用

大语言模型&#xff08;Large Language Models,LLMs&#xff09;通过API&#xff08;应用程序接口&#xff09;为开发者提供了便捷的调用方式&#xff0c;使其能够快速集成自然语言处理能力到各类应用中。以下是API在LLM中的核心应用场景及技术实现细节&#xff1a; 一、核心应…

33-盛最多水的容器

给定一个长度为 n 的整数数组 height 。有 n 条垂线&#xff0c;第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。 找出其中的两条线&#xff0c;使得它们与 x 轴共同构成的容器可以容纳最多的水。 返回容器可以储存的最大水量。 说明&#xff1a;你不能倾斜容器。 方法…

电商项目Ts版本

文章目录 项目地址一、环境安装1.1 配置作为导入1.2 文件目录 二、路由2.1 publicRoutes 项目地址 教程作者&#xff1a;教程地址&#xff1a; 代码仓库地址&#xff1a; 所用到的框架和插件&#xff1a; dbt airflow一、环境安装 1.1 配置作为导入 vite.config.ts impor…