需求:
业务需要每月固定给客户导出报告,后台导出时只需要将数据查出,然后实现自动将数据插入到word模版文件里。
实现此项功能之前需要学习freemarker语法。
实现逻辑:
- 创建word模版,编辑需要插入数据的地方
2. 保存为xml文件,修改后缀名为ftl文件
3. 将文件放到resources/templates目录下
- 编写代码
添加依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
生成方法:
public void generateFile() throws IOException, TemplateException {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
configuration.setDefaultEncoding("UTF-8");
// freemarker在加载模板时,建议使用TemplateLoader,通过TemplateLoader指定从哪个目录开始加载模板,并且把模板加载在缓存中
TemplateLoader templateLoader = new FileTemplateLoader(new File("D:"));
// 模版文件路径
String path = "\\src\\main\\resources\\ftl\\学习模版导出.ftl";
// 指定类所在的目录来指定模板所在根路径
configuration.setTemplateLoader(templateLoader);
// 获取项目中模版资源
Template template = configuration.getTemplate(path, "UTF-8");
// 要放入模版中的数据
Map<String, String> data = new HashMap<>();
data.put("companyName", "家里蹲");
data.put("name", "老子");
// 生成文件
File file = new File("D:/work/finalFile.docx");
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
template.process(data, writer);
writer.close();
}
此种模版为最初级模版,若需要列表遍历或报告中含有图标实现需要更深入学习freemarker模版文件导出实现,后续有空会进行更新。