1,修改模板文件
把需要导出文件的数据以${deputyName}的格式弄好,如下图所示
然后把修改好的.doc文件另存为xml文件
2,.xml文件转换为模板导出所需的.ftl文件
直接改文件后缀可能会有格式问题,这里提供一个转换的方法:FileReader fr = new FileReader(new File("C:\\Users\\DragonSea1\\Desktop\\20201013新增内容\\ContactStationDataStatistical.xml"));
char[] chars = new char[1024];
int len;
StringBuffer sb = new StringBuffer();
StringBuffer inner = new StringBuffer();
int f = 0;
int b = 0;
while ((len = fr.read(chars)) != -1) {
for (int i = 0; i < len; i++) {
if (chars[i] == '') {
f = 0;
sb.append(chars[i]);
continue;
}
if (f == 1) {
sb.append(chars[i]);
}
//xml 内部内容
if (f == 0) {
if (chars[i] == '$') {
b = 1;
inner.append(chars[i]);
continue;
}
if (chars[i] == '}' && b == 1) {
b = 0;
inner.append(chars[i]);
sb.append(inner.toString());
//重建 sb
inner = new StringBuffer();
continue;
}
if (b == 1) {
inner.append(chars[i]);
continue;
}
sb.append(chars[i]);
}
}
}
FileWriter fw = new FileWriter(new File("C:\\Users\\DragonSea1\\Desktop\\20201013新增内容\\ContactStationDataStatistical.ftl"));
fw.write(sb.toString());
fw.flush();
fw.close();
fr.close();
System.out.println("处理完成");
}
生成的ftl文件
3,获取数据并导出
模板导出需要用到freemarker的包
org.springframework.boot
spring-boot-starter-freemarker
获取数据放在一个map里面,然后就可以导出了,这里直接贴代码//存放数据的map
MapdataMap = new HashMap();
//获取数据的方法这里不多描述,和模板的${deputyName}对应就好
//简单例子: dataMap.put("deputyName", "测试名字");
//Configuration 用于读取ftl文件
Configuration configuration = new Configuration(new Version("2.3.0"));
configuration.setDefaultEncoding("utf-8");
configuration.setClassicCompatible(true);
/**
* 以下是两种指定ftl文件所在目录路径的方式,注意这两种方式都是
* 指定ftl文件所在目录的路径,而不是ftl文件的路径
*/
//获取相对路径
ApplicationHome h = new ApplicationHome(getClass());
File jarF = h.getSource();
ClassPathResource classPathResource = new ClassPathResource("/");
ClassLoader classLoader = classPathResource.getClassLoader();
configuration.setClassLoaderForTemplateLoading(classLoader, "template");
//输出文件的路径
String path = jarF.getParentFile().toString() + "/temp/" + originalFilename + ".doc";
File outFile = new File(path);
if (!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdirs();
}
//以utf-8的编码读取ftl文件
Template template = configuration.getTemplate(originalFilename + ".ftl", "utf-8");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
template.process(dataMap, out);
out.close();
这里注意的是,模板导出word需要获取模板文件的文件目录的路径
4,导出效果
这里只针对简单导出,需要导出带有图片的和循环导出的,后续再出教程