【java】Freemarker 动态生成word(带图片表格)

1、添加freemarker.jar 到java项目。

2、新建word文档。

3、将文档另存为xml 格式。

4、将xml格式化后打开编辑(最好用notepad,有格式),找到需要替换的内容,将内容换为变量(${变量名})。

5、生成表格,包括动态列和动态行。其中columnList 是List<String>格式的表头数据,datas 是List<List<String>>格式的全部表格数据。

<w:tblGrid>
<#list columnList as columnName>
<w:gridCol w:w="1579"/>
</#list>
</w:tblGrid>
<#list datas as entity>
<w:tr wsp:rsidR="0015753E" wsp:rsidRPr="00765BE2" wsp:rsidTr="00765BE2">
<#list entity as cell>

<w:tc>
<w:tcPr>
<w:tcW w:w="853" w:type="dxa"/>
<w:shd w:val="clear" w:color="auto" w:fill="auto"/>
</w:tcPr>
<w:p wsp:rsidR="0015753E" wsp:rsidRPr="00765BE2" wsp:rsidRDefault="007C79C8" wsp:rsidP="00765BE2">
<w:pPr>
<w:jc w:val="center"/>
</w:pPr>
<w:r wsp:rsidRPr="00765BE2">
<w:rPr>
<wx:font wx:val="宋体"/>
</w:rPr>
<w:t>${cell}</w:t>
</w:r>
</w:p>
</w:tc>
</#list>
</w:tr>
</#list>

6、生成图片。将xml文件中<w:binData></w:binData> 中的数据替换成需要的图片的base64编码即可。

7、保存后,将文件后缀改为.ftl,放到java项目文件夹。生成word:

Map<String, Object> map = new HashMap<String, Object>();
map.put("变量名", 变量内容);

 

public static void createWord(Map<String, Object> 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();
}
}

 

posted @ 2018-07-20 14:23  wkYLduoduo  阅读(1588)  评论(0编辑  收藏  举报