通过Ftl模版创建doc文件步骤:
- 首先需要创建word文档模板
- word模板中要动态生成的文字都使用占位符${string}代替,与填充参数dataMap的key对应。
- 将word模板另存为xml文件
- 将文件的后缀.xml改为.ftl
- 将.ftl模板文件放到指定目录(该示例放在项目的resource目录)
注意事项:
- 千万不要使用代码格式化(可以xml格式化),否则模版的格式会被改变!
- ftl模板文件有时候占位符会被拆分,需手动修改。
import cn.hutool.core.io.file.FileWriter;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import java.io.*;
import java.util.Map;
public static void createDocByFtl(String tempPath, String fileSavePath, String tempFtl, Map<String, Object> dataMap, String docFileName) {
Writer out = null;
try {
InputStream stream = TemplateUtil.class.getClassLoader().getResourceAsStream(tempFtl);
FileWriter fileWriter = new FileWriter(tempPath + File.separator + tempFtl);
fileWriter.writeFromStream(stream);
Configuration configuration = new Configuration(new Version("2.3.0"));
//模板文件所在路径
configuration.setDirectoryForTemplateLoading(new File(tempPath));
//获取模板文件
Template template = configuration.getTemplate(tempFtl);
//导出文件
File outFile = new File(fileSavePath + File.separator + docFileName + ".doc");
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
//将填充数据填入模板文件并输出到目标文件
template.process(dataMap, out);
} catch (Exception e) {
System.out.println(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
}
动态表格示例,找到表格最后一列的位置添加<#list map中集合key变量名 as item>标签,结束的位置添加 ,列名为 item.xx
<w:p>
<w:pPr>
<w:spacing w:line="300" w:line-rule="exact"/>
<w:jc w:val="center"/>
<w:rPr>
<w:rFonts w:ascii="宋体;SimSun" w:h-ansi="宋体;SimSun" w:cs="宋体;SimSun" w:hint="default"/>
<w:sz-cs w:val="21"/>
</w:rPr>
</w:pPr>
<w:r>
<w:rPr>
<w:rFonts w:ascii="宋体;SimSun" w:h-ansi="宋体;SimSun" w:cs="宋体;SimSun" w:hint="default"/>
<w:sz-cs w:val="21"/>
</w:rPr>
<w:t>表格最后一列名</w:t>
</w:r>
</w:p>
</w:tc>
</w:tr>
<#list map中集合key变量名 as item>
<w:tr>
<w:tblPrEx>
<w:tblBorders>
<w:top w:val="single" w:sz="4" wx:bdrwidth="10" w:space="0" w:color="000000"/>
<w:left w:val="single" w:sz="4" wx:bdrwidth="10" w:space="0" w:color="000000"/>
<w:bottom w:val="single" w:sz="4" wx:bdrwidth="10" w:space="0" w:color="000000"/>
<w:right w:val="nil"/>
<w:insideH w:val="single" w:sz="4" wx:bdrwidth="10" w:space="0" w:color="000000"/>
<w:insideV w:val="nil"/>
</w:tblBorders>
<w:tblCellMar>
省略…… <w:r>
<w:rPr>
<w:rFonts w:ascii="宋体;SimSun" w:h-ansi="宋体;SimSun" w:cs="宋体;SimSun" w:hint="fareast"/>
<w:sz-cs w:val="21"/>
<w:lang w:val="EN-US" w:fareast="ZH-CN"/>
</w:rPr>
<w:t>${item.xx}</w:t>
</w:r>
</w:p>
</w:tc>
</w:tr>
</#list>