第一、导入依赖 <!-- docx 数据填充生成 doc文件 这个是主要 --> <!-- POI --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>4.1.2</version> </dependency> <!-- poi-tl --> <dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.10.0</version> </dependency>
第二、配置maven打包,过滤掉word文件,不加以编码,否则会报错
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.1.0</version> <configuration> <encoding>UTF-8</encoding> <nonFilteredFileExtensions> <!-- Caused by: java.util.zip.ZipException: Unexpected record signature: 0X9 应该是编译代码时,把excel模板文件也重新编码了,导致excem模板文件格式损坏 需要过滤掉不需要编码的文件:过滤后缀为.xlsx或者.xls,docx后者doc的所有文件,不对其进行统一编码--> <nonFilteredFileExtension>xlsx</nonFilteredFileExtension> <nonFilteredFileExtension>xls</nonFilteredFileExtension> <nonFilteredFileExtension>docx</nonFilteredFileExtension> <nonFilteredFileExtension>doc</nonFilteredFileExtension> <nonFilteredFileExtension>pptx</nonFilteredFileExtension> <nonFilteredFileExtension>ppt</nonFilteredFileExtension> </nonFilteredFileExtensions> </configuration> </plugin>
第三、编写测试代码
@GetMapping("/filld") @ApiOperation("测试word代码填充") public void zipDdownload2(HttpServletRequest request, HttpServletResponse response) throws IOException { Map<String, Object> params = new HashMap<>(); params.put("legalCode","dddd"); params.put("channel","数智xxx"); Resource resource = new ClassPathResource("templates_report/2.docx"); File file = resource.getFile(); //创建输出流 OutputStream os = new FileOutputStream("template1_out.docx"); //最终编译渲染并输出 XWPFTemplate.compile(file).render(params).writeAndClose(os); System.out.println("输出完毕"); }