一、准备
添加依赖
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.7.3</version>
</dependency>
定义模板
注意:需要把模板放在springboot项目的resources目录下,我这边放在了resources/template下
说明:
{{googslist}}这个是用来渲染动态表格标记点,定义这个后,才能在指定位置渲染
二、后台代码
@Controller
public class Test {
@GetMapping("downloadWorld")
public void downloadWorld(HttpServletResponse response,String hiddenDangerId){
Map<String, Object> data = new HashMap<>();
data.put("center","这个是简单描述内容");
//创建表格数据
List<Map<String, Object>> goodsList = new ArrayList<>();
Map<String,Object> d1 = new HashMap<String, Object>();
d1.put("name","手机");
d1.put("googsNum","10");
goodsList.add(d1);
//渲染表格
HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
//注意goodslist就是表格上定义的goodslist
Configure config = Configure.newBuilder().bind("goodslist", policy).build();
data.put("goodslist",goodsList);
//本地测试这样写
// ClassPathResource classPathResource = new ClassPathResource("/template/test.docx");
// String path = classPathResource.getURL().getPath();
// XWPFTemplate template = XWPFTemplate.compile(path,config).render(data);
//渲染数据
//这种写法支持打包成jar在linux服务器中使用能解决掉文件获取不到的问题
XWPFTemplate template = XWPFTemplate.compile(WordUtil.class.getClassLoader().getResourceAsStream("template/test.docx"),config).render(data);
downloadServlet(template,response);
}
private static void downloadServlet(XWPFTemplate template, HttpServletResponse response){
try{
response.setHeader("Content-disposition", "attachment;filename=" + new String("model".getBytes("gb2312"), "ISO8859-1") + ".docx");
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
response.setContentType("multipart/form-data;charset=UTF-8");
ServletOutputStream out = response.getOutputStream();
template.write(out);
out.flush();
template.close();
out.close();
}catch (Exception e){
e.getMessage();
}
}
}