Springboot 之 POI导出Word文件

本文章来自【知识林】

导出Word文件其实与Springboot没有多大关系,这都是Apache子项目POI的功劳。下面简单介绍一下在Springboot项目中如何使用POI导出Word文件。

  • pom.xml文件
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.15</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-scratchpad</artifactId>
        <version>3.15</version>
    </dependency>
</dependencies>

关键的依赖是poi的jar包:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.15</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>3.15</version>
</dependency>
  • 创建Word模板文件

创建一个Word文件,命名为:template.doc,内容如图:

POI导出Word文件的模板

  • 编写导出程序
private void build(File tmpFile, Map<String, String> contentMap, String exportFile) throws Exception {
    FileInputStream tempFileInputStream = new FileInputStream(tmpFile);
    HWPFDocument document = new HWPFDocument(tempFileInputStream);
    // 读取文本内容
    Range bodyRange = document.getRange();
    // 替换内容
    for (Map.Entry<String, String> entry : contentMap.entrySet()) {
        bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
    }

    //导出到文件
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    document.write(byteArrayOutputStream);
    OutputStream outputStream = new FileOutputStream(exportFile);
    outputStream.write(byteArrayOutputStream.toByteArray());
    outputStream.close();
}

参数说明:

tmpFile: 模板文件

contentMap:数据模型,包含具体数据的map对象

exportFile:需要保存导出文件的路径

  • 导出文件测试方法
@Test
public void testExportWord() throws Exception {
    String tmpFile = "D:/temp/template.doc";
    String expFile = "D:/temp/result.doc";
    Map<String, String> datas = new HashMap<String, String>();
    datas.put("title", "标题部份");
    datas.put("content", "这里是内容,测试使用POI导出到Word的内容!");
    datas.put("author", "知识林");
    datas.put("url", "http://www.zslin.com");

    build(new File(tmpFile), datas, expFile);
}

注意:这里的模板文件是放到D:/temp目录下,在实际项目应用中这些模板文件都是需要放在项目的classpath中的,这样的做法很明显不能满足需求。

  • 模板文件中classpath中的导出文件测试方法
@Test
public void testExportWord2() throws Exception {
    String tmpFile = "classpath:template.doc";
    String expFile = "D:/temp/result.doc";
    Map<String, String> datas = new HashMap<String, String>();
    datas.put("title", "标题部份");
    datas.put("content", "这里是内容,测试使用POI导出到Word的内容!");
    datas.put("author", "知识林");
    datas.put("url", "http://www.zslin.com");

    build(ResourceUtils.getFile(tmpFile), datas, expFile);
}

注意: 使用ResourceUtils工具类的getFile方法即可读取classpath中的文件,所以这里读模板文件的方法是:ResourceUtils.getFile("classpath:template.doc")

以上两种方法导出的文件都放在:D:/temp/result.doc文件中,具体的内容如下图:

POI导出Word的结果图片

示例代码:https://github.com/zsl131/spring-boot-test/tree/master/study14

本文章来自【知识林】

要实现Spring Boot和Vue导出Word文档,可以使用poidocx4j这两个工具。 首先是后端Spring Boot的实现: 1. 添加poidocx4j依赖到pom.xml文件中: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.docx4j</groupId> <artifactId>docx4j</artifactId> <version>11.3.3</version> </dependency> ``` 2. 创建Word导出接口: ```java @RestController @RequestMapping("/export") public class ExportController { @GetMapping("/word") public void exportWord(HttpServletResponse response) throws Exception { // 创建一个空白的Word文档 WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); // 添加段落 wordMLPackage.getMainDocumentPart().addParagraphOfText("Hello, World!"); // 设置响应头 response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); response.setHeader("Content-Disposition", "attachment; filename=test.docx"); // 输出Word文档 wordMLPackage.save(response.getOutputStream()); } } ``` 3. 启动Spring Boot应用,访问http://localhost:8080/export/word即可下载导出Word文档。 然后是前端Vue的实现: 1. 安装axios和file-saver依赖: ```bash npm install axios file-saver --save ``` 2. 创建导出Word的方法: ```js exportWord() { axios({ method: 'get', url: '/export/word', responseType: 'blob' }).then(response => { const blob = new Blob([response.data]); const fileName = 'test.docx'; saveAs(blob, fileName); }); } ``` 3. 在Vue组件中添加一个按钮,并绑定导出Word的方法: ```html <template> <div> <button @click="exportWord">导出Word</button> </div> </template> <script> import axios from 'axios'; import { saveAs } from 'file-saver'; export default { name: 'Export', methods: { exportWord() { axios({ method: 'get', url: '/export/word', responseType: 'blob' }).then(response => { const blob = new Blob([response.data]); const fileName = 'test.docx'; saveAs(blob, fileName); }); } } }; </script> ``` 4. 运行Vue应用,点击按钮即可下载导出Word文档。 以上就是Spring Boot和Vue导出Word文档的实现步骤,希望能对你有帮助!
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值