代码:
package com.wangtiansoft.stla.provider.utils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.util.*;
public class WordUtil {
/**
* 生成word文件
* @param dataMap word中需要展示数据
* @param templateName word模板名称,例如:1.ftl
* @param filePath 文件生成的目标路径,例如:D:/doc/
* @param fileName 生成的文件名称,例如:test.doc
*/
public static void createWord(Map dataMap,String templateName,String filePath,String fileName){
try {
//创建配置实例
Configuration configuration = new Configuration();
//设置编码
configuration.setDefaultEncoding("UTF-8");
//ftl模板文件
configuration.setClassForTemplateLoading(WordUtil.class,"/");
//获取模板
Template template = configuration.getTemplate(templateName,"UTF-8");
//输出文件
File outFile = new File(filePath+File.separator+fileName);
//如果输出目标文件夹不存在,则创建
if (!outFile.getParentFile().exists()){
outFile.getParentFile().mkdirs();
}
//将模板和数据模型合并生成文件
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
//生成文件
template.process(dataMap, out);
//关闭流
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Map<String, Object> dataMap = new HashMap<String, Object>();
List<Object> datas = new ArrayList<>();
dataMap.put("date1","2020.3.9");
dataMap.put("date2","2020.3.10");
dataMap.put("fileName","fileName");
//文件路径
String filePath = "D:/doc/";
//文件名称
String fileOnlyName = "文档.doc";
//生成word 数据包装,模板名,文件生成路径,生成的文件名
WordUtil.createWord(dataMap, "1.ftl", filePath, fileOnlyName);
}
}
具体说明:
其中的1.ftl是word的模板,内容:
ftl制作步骤:
- word模板中需要替换的动态数据用${}占位符占位,占位的每个字段都是你所需要放到map里面的字段
- 将word另存为xml格式
- 然后使用可以编辑xml的软件打开,我是直接用的idea打开的,里面有一些是错误的格式比如说:
直接删除红色标记的这一行在{data2}前面加上 {data2}这样的格式,修改所有 - 然后将文件后缀改成ftl就行了
- 可以运行main方法就ok了