1、添加freemarker.jar 到java项目。
2、新建word文档。
3、将文档另存为xml 格式。
4、将xml格式化后打开编辑(最好用notepad,有格式),找到需要替换的内容,将内容换为变量(${变量名})。
5、生成表格,包括动态列和动态行。其中columnList 是List格式的表头数据,datas 是List>格式的全部表格数据。
#list>
${cell}
#list>
#list>
6、生成图片。将xml文件中 中的数据替换成需要的图片的base64编码即可。
7、保存后,将文件后缀改为.ftl,放到java项目文件夹。生成word:
Map map = new HashMap();
map.put("变量名", 变量内容);
public static void createWord(Map map, String filePath) {
try {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
configuration.setClassForTemplateLoading(TemplateToWord.class, "/com/cn/templates/");//模板所在文件夹
Template template = configuration.getTemplate("report.ftl");//根据名称加载模板
File outFile = new File(filePath);//生成新word文档
if (!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdirs();
}
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
// 生成文件
template.process(map, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}