Springboot如何利用模板,快速生成word文档?

159 阅读2分钟

前言

大家好,我是小徐啊。我们在使用SpringBoot开发的时候,有时候会遇到需要生成word文档的情况。一般情况下,就是将一些数据填充到word文档里面。其实Java是有开源的第三方jar包的。今天,小徐就来介绍下如何在SpringBoot里面生成word文档。

如何设置

首先,我们需要在pom.xml文件里面,引入deepoove的依赖,如下所示。

0

com.deepoove poi-tl 1.10.0

然后,我们需要自己写一个WordUtil类,这样做是为了方便,当然也可以不写工具类。这里,主要是写好word模板的路径,生成word的路径,然后,再在里面填充对应的参数和参数值,比如这里填充了today这个参数和参数值。其他的写法就参考如下代码即可。

0

public class WordUtil { public String insertWord(SecurityDailyInfoVO securityDailyInfoVO,String serviceDirectoryPath,String out){ try { String today = DateUtil.daFormat(securityDailyInfoVO.getCreateTime()); Map map = new HashMap<String, Object>(); map.put("today", today); XWPFDocument document = null; InputStream inputStream = new FileInputStream(serviceDirectoryPath+ File.separator+"temp.docx"); document = new XWPFDocument(inputStream); //document.enforceReadonlyProtection("123", HashAlgorithm.md5); //document.enforceFillingFormsProtection("456", HashAlgorithm.sha512); String outPath = out + File.separator + "SecurityDailyReport_" + today + ".docx"; XWPFTemplate.compile(document).render(map).writeToFile(outPath); return outPath; } catch ( IOException e) { e.printStackTrace(); return null; } } }

最后,在word的模板里面,把需要填充的地方,输入参数,用双大括号括起来,这样到时候就可以自动填充数据了。是不是很方便?

0

总结

好了,今天就讲到这儿啦。以上就是在springboot里面生成word文档的操作方法了,感谢你的阅读。

如果有对Java入门开发相关的问题,可访问我的个人网站:idea-tips.com/

往期推荐:

1.navicat如何导出数据?附navicat15安装包

2.一个程序员的水平能差到什么程度?有时候,差只是表象...

3.为什么很多老程序员不建议编程新手用IDE?

4.IDEA如何快速选中一个词、一行、一个方法?