利用poi-tl实现word模板替换功能
Poi-tl是基于Apache POI的Word模板引擎,纯JAVA组件。
API地址:http://deepoove.com/poi-tl/
实现过程:
系统中提供word模板上传功能,将word模板上传至指定位置
获取word模板,利用poi-tl生成替换后的word文档
返回OutputStream,调用浏览器下载
1、引入poi-tl
com.deepoove
poi-tl
1.5.0
若在使用过程出现NoClassDefindException,可以尝试引入如下依赖(非必须)
org.apache.poi
ooxml-schemas
1.3
org.apache.commons
commons-collections4
4.1
org.apache.xmlbeans
xmlbeans
2.3.0
2、使用poi-tl
1)文本替换{{var}}
/**
* 文本替换 {{title}}
* @throws Exception
*/
@GetMapping("/text")
public void testText(HttpServletResponse response) throws Exception{
XWPFTemplate template = XWPFTemplate.compile("src\\word-template\\testText.docx").render(new HashMap(){{
put("func", "数据模型与样式的分离");
put("title", "Poi-tl 模板引擎");
}});
response.setContentType("application/x-download");
response.setHeader("Content-Disposition","attachment;filename=testText_replace.docx");
OutputStream out = response.getOutputStream();
//FileOutputStream out = new FileOutputStream("d:\\word_replace\\testText_replace.docx");
template.write(out);
out.flush();
out.close();
template.close();
}
2)插入表格{{#var}}
用于向word中插入一个全新的表格
/**
* 插入表格 {{#table}}
* @throws Exception
*/
@GetMapping("/createTable")
public void testCreateTable(HttpServletResponse response) throws Exception{
Style headerStyle = new Style();
headerStyle.setBold(true);