基础操作
- 本质上是通过占位符进行内容替换
- 本文章仅操作docx格式的文档
.doc (Word 97-2003): 使用OLE2格式,对应POI的 HWPF 组件
.docx (Word 2007+): 使用OOXML格式,对应POI的 XWPF 组件
基础操作_模板部分

- 将模板放入resources 资源目录下,自定义文件夹中,例如:templet/word_template/demo_template.docx
代码部分
- maven
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.12.1</version>
</dependency>
- 处理过程
String templateFilePath = "templet/word_template/demo_template.docx";
InputStream templateIn = getClass().getClassLoader().getResourceAsStream(templateFilePath);
Map<String, Object> templateData = new HashMap<String, Object>();
templateData.put("str1", "替换成功");
XWPFTemplate template = XWPFTemplate.compile(templateIn).render(templateData);
template.writeAndClose(new FileOutputStream("D:/output.docx"));
templateIn.close();
- 此时,文件便下载到了 D:/output.docx 的位置。
- 若为Web
public void pgdExport(HttpServletResponse response) throws IOException {
String templateFilePath = "templet/word_template/demo_template.docx";
InputStream templateIn = getClass().getClassLoader().getResourceAsStream(templateFilePath);
Map<String, Object> templateData = new HashMap<String, Object>();
templateData.put("str1", "替换成功");
XWPFTemplate template = XWPFTemplate.compile(templateIn).render(templateData);
ServletOutputStream outputStream = response.getOutputStream();
String fileName = "文件名.docx";
String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=utf-8''" + encodedFileName);
response.setCharacterEncoding("UTF-8");
template.writeAndClose(outputStream);
templateIn.close();
}
window.location.href = '你的接口地址';
插入图片
- 模板:占位符格式是{{@xxxx}}

- 代码
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
templateData.put("img", Pictures.ofStream(in, PictureType.JPEG).size(300, 300).create());
参考文章
- https://blog.csdn.net/weixin_44496396/article/details/140066940