1.Apache POI
@GetMapping("data") public void data(HttpServletResponse response) throws Exception { response.setContentType("application/msword;charset=utf-8"); response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("test.docx", "utf-8")); ClassLoader classLoader = getClass().getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream("templates/test.docx"); XWPFDocument document = new XWPFDocument(inputStream); List<XWPFParagraph> paragraphs = document.getParagraphs(); for (XWPFParagraph paragraph : paragraphs) { List<XWPFRun> runs = paragraph.getRuns(); for (XWPFRun run : runs) { String text = run.getText(0); text = text.replace("{{name}}", "张三"); run.setText(text,0); } } ServletOutputStream outputStream = response.getOutputStream(); document.write(outputStream); outputStream.flush(); }
2.poi-tl<dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.12.1</version> </dependency>
使用 {{name}} 作为word中的占位符
@Override public void test(HttpServletResponse response) { try { response.setContentType("application/msword;charset=utf-8"); response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("test.docx", "utf-8")); ClassLoader classLoader = getClass().getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream("templates/test.docx"); Map<String, Object> dataModel = new HashMap<>(); dataModel.put("name", "张三"); XWPFTemplate render = XWPFTemplate.compile(inputStream).render(dataModel); ServletOutputStream outputStream = response.getOutputStream(); render.write(outputStream); outputStream.flush(); } catch (Exception e) { throw new ServiceException(下载异常); } }