一、依赖
<dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.12.0</version> </dependency>
二、word模板
桌面新建demo.docx,内容如下
{{title}}
三、替换模板并输出
@GetMapping("getDoc") public void getDoc(HttpServletResponse response) throws IOException { String templeteDocx = "C:\\Users\\Administrator\\Desktop\\demo.docx"; //获取word模板和填充数据 XWPFTemplate template = XWPFTemplate.compile(templeteDocx).render( new HashMap<String, Object>(){{ put("title", "Hi, poi-tl Word模板引擎"); }}); //设置返回类型及文件名 response.setContentType("application/octet-stream"); response.setHeader("Content-disposition","attachment;filename=\""+"out_template.docx"+"\""); //获取返回输出流 OutputStream out = response.getOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(out); template.write(bos); bos.flush(); out.flush(); PoitlIOUtils.closeQuietlyMulti(template, bos, out); } @GetMapping("markDoc") public void markDoc(HttpServletResponse response) throws IOException { //末班位置 String templeteDocx = "C:\\Users\\Administrator\\Desktop\\demo.docx"; //获取word模板和填充数据 XWPFTemplate template = XWPFTemplate.compile(templeteDocx).render( new HashMap<String, Object>(){{ put("title", "Hi, poi-tl Word模板引擎"); }}); template.writeAndClose(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\output.docx")); }
四、测试
#生成word并下载 http://localhost:6565/getDoc #生成word到指定位置 http://localhost:6565/markDoc