这是我参与8月更文挑战的第1天,活动详情查看:8月更文挑战
springboot使用freeMaker导出word
1、pom依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.ftl</include>
</includes>
</resource>
2、工具类
package org.springblade.common.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* 功能描述:
*
* @Author:
* @Date: 2021/8/4 13:41
*/
public class DocumentHandler {
private Configuration configuration = null;
public DocumentHandler() {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}
public void createDoc(Map<String,Object> dataMap,String fileName,String template) throws UnsupportedEncodingException {
//dataMap 要填入模本的数据文件
//设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
//这里我们的模板是放在template包下面
configuration.setClassForTemplateLoading(this.getClass(), "/templates");
Template t=null;
try {
//test.ftl为要装载的模板
t = configuration.getTemplate(template);
} catch (IOException e) {
e.printStackTrace();
}
//输出文档路径及名称
File outFile = new File(fileName);
Writer out = null;
FileOutputStream fos=null;
try {
fos = new FileOutputStream(outFile);
OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
//这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(oWriter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
out.close();
fos.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、调用工具类使用
生成的word在C盘a文件夹下
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("stat",123);
dataMap.put("startDate",123);
dataMap.put("endDate",123);
dataMap.put("zhu",123));
dataMap.put("szdxsj",123);
DocumentHandler mdoc = new DocumentHandler();
mdoc.createDoc(dataMap, "
C:/a/信息.doc","信息.ftl");
4、ftl模板生成规则
自定义word模板,另存为xml,将xml打开,修改里面的常量改为变量,变量需符合freemarker语法,然后另存为ftl文件
<w:r>
<w:rPr>
<w:rFonts w:fareast="仿宋_GB2312" w:hint="fareast"/>
<w:kern w:val="0"/>
<w:sz w:val="32"/>
<w:sz-cs w:val="32"/>
<w:lang w:val="EN-US" w:fareast="ZH-CN"/>
</w:rPr>
<w:t>${szdxsj}</w:t>
</w:r>