1:导入freemarker包文件
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
2:准备模板文件
本文主要介绍根据模板生成文件的方式,所以先准备好一个模板文件,修改模板文件中的内容进行准备操作。
红色箭头指向的是占位符,代表了我想要更改数据,更改这个表格内的数据。
蓝色箭头同理也是占位符,不过这里需要进行列表生成,所以使用不同的占位符来占用。
准备好的文件格式为ftl
格式,生成这种格式的方法为:*.doc/*.docx/*.xls/*.xlsx -> *.xml -> *.ftl
。
其中*.doc/*.docx/*.xls/*.xlsx
生成 *.xml
时,使用另存为来进行保存,当xml
生成 ftl
时,只需要更改文件的后缀即可。
3:处理列表占位符
上个步骤提到了列表的占位符,需要编辑 ftl
文件,让程序知道我要在这里生成一个列表,而不是普通的文本数据。
根据图中添加<#list>
来表示这里是一个集合输出,括在<Row>
外,则代表需要整行遍历,具体不再阐述。
更改完成之后保存文件,编写Java
程序来生成。
4:编写程序
package com.xiaofsu.excel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.util.*;
public class ExcelTemplate {
public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\xiaoFsu\\Desktop"));
Template template = configuration.getTemplate("test.ftl");
Map<String, Object> dataMap = new HashMap<String, Object>();
// 公用
dataMap.put("a", "a");
dataMap.put("b", "b");
dataMap.put("c", "c");
dataMap.put("d", "d");
dataMap.put("e", "e");
dataMap.put("f", "f");
dataMap.put("g", "g");
dataMap.put("s", "s");
dataMap.put("u", "u");
dataMap.put("v", "v");
dataMap.put("w", "2020");
dataMap.put("x", "10");
dataMap.put("y", "23");
// 生成集合使用这种方式来操作
List<Map<String,Object>> testList= new ArrayList<>();
for (int i = 0; i < 5; i++) {
Map<String,Object> map = new HashMap<>();
map.put("h",i);
map.put("i",i);
map.put("j",i);
map.put("k",i);
map.put("l",i);
map.put("m",i);
map.put("n",i);
map.put("o",i);
map.put("p",i);
map.put("q",i);
map.put("r",i);
testList.add(map);
}
dataMap.put("list", testList);
File outFile = new File("C:\\Users\\xiaoFsu\\Desktop\\test1.xlsx");
FileOutputStream fos = new FileOutputStream(outFile);
Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
template.process(dataMap, out);
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
调整模板位置及输出的文件路径,这样就可以生成数据了。
5:总结
在处理word
时,处理方式相同于excel
。
处理多个sheet
时,相同与第一个处理,使用占位符进行占位进行替换即可。(另存为xml时,多个sheet
保存到同一个文件中,以某标签分割。)
Q.E.D.