使用FreeMarker自动生成Word文档
- 获取文件路径
创建一个word文档,然后再文档中在文档中写标识,对应代码中的map数据
2.将word转为xml后缀文件,再转为.ftl文件
3.保存路径
String resource1 = "D:/pageoffice/abc.doc";
4.组装数据
Map<String, Object> dataMap = new HashMap<>();
// 工程概况信息
dataMap.put("projectOverview",wkProjectItem.getProjectOverview();
boolean b = generateWord(dataMap , resource1);
/**
* 使用FreeMarker自动生成Word文档
*
* @param dataMap 生成Word文档所需要的数据
* @param fileName 生成Word文档的全路径名称
*/
public static boolean generateWord (Map < String, Object > dataMap, String fileName, String docType){
// 设置FreeMarker的版本和编码格式
Configuration configuration = new Configuration(new Version("2.3.28"));
configuration.setDefaultEncoding("UTF-8");
try {
String resource = getFileUrl();
// 设置FreeMarker生成Word文档所需要的模板的路径
//configuration.setClassForTemplateLoading(this.getClass(),"/template");C:\Users\Administrator\Desktop\aa\测试12\分解
configuration.setDirectoryForTemplateLoading(new File(resource));
// 设置FreeMarker生成Word文档所需要的模板
Template t = null;
t = configuration.getTemplate("/excel/es1.ftl", "UTF-8");
// 创建一个Word文档的输出流
//OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), StandardCharsets.UTF_8));
//FreeMarker使用Word模板和数据生成Word文档
t.process(dataMap, out);
out.flush();
out.close();
return true;
} catch (IOException | TemplateException ioException) {
ioException.printStackTrace();
return false;
}
}