返回导航页
业务来源
需要将一些信息,生成word然后导出来。
工具推荐
开源的,非常好用,直接跑个demo,你就能体会多方便了!
deepoove
直接安排个demo
操作word和操作excel不太一样,操作word首先需要准备一个模板,需要填充内容的地方,使用占位符,先把位置占好,然后在业务中进行占位符填充!
我解释明白了吗?
不明白?那直接截图官方文档吧!!!
还不明白?那直接看我写的吧!
安排!
第一步
第二步
第三步
多种输出方式,这里代码演示网络流的输出!
/**获取报告*/
@RequestMapping("/download/word**/***")
public void downloadWord(HttpServletResponse response) throws Exception {
XWPFTemplate template = XWPFTemplate.compile("src/main/resources/template.docx").render(
new HashMap<String, Object>(){{
put("title", "这个是标题哈,填充进去");
}});
// 文件流传输
// template.writeAndClose(new FileOutputStream("output.docx"));
// 使用网络流进行传输
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition","attachment;filename=\""+"输出文件.docx"+"\"");
// HttpServletResponse response
OutputStream out = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(out);
template.write(bos);
bos.flush();
out.flush();
PoitlIOUtils.closeQuietlyMulti(template, bos, out);
}
postman测试一把咯
文件名中文的有问题,后续在处理吧!
不过内容没得问题了。
大坑
################################大坑#########################################
springboot打成jar包,会导致目录结构发生改变,绝对路径是没有用的;
这个问题太坑了,
本地测试都没有问题,上测试环境就出现问题了!!!!
还有就是处理中文乱码问题。
解决方法:
使用流
/**获取报告*/
@RequestMapping("/download/word**/***")
public void downloadWord(HttpServletResponse response) throws Exception {
ClassPathResource resource = new ClassPathResource("template.docx");
InputStream inputStream = resource.getInputStream();
XWPFTemplate template = XWPFTemplate.compile(inputStream).render(
new HashMap<String, Object>(){{
put("title", "这个是标题哈,填充进去");
}});
// 文件流传输
// template.writeAndClose(new FileOutputStream("output.docx"));
// 使用网络流进行传输
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("小可爱文档.docx", "UTF-8"));
// HttpServletResponse response
OutputStream out = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(out);
template.write(bos);
bos.flush();
out.flush();
PoitlIOUtils.closeQuietlyMulti(template, bos, out);
}