JAVA 根据模板生成doc文件
需求
根据模板生成对应的doc文档,文档内容动态填充。
实现
1.将doc模板转换为ftl文件,放入项目中
1.1 首先将模板另存为xml文件
1.2 更改xml文件后缀为ftl,即可把doc转为ftl.
2.代码实现
2.1 首先根据自身需求获取文档动态内容的数据,由于业务不同,这里不做过多阐述,我这里数据的返回类型为MAP.
2.2 通过调用方法,生成文档并通过浏览器下载
public static void WordExport(Map dataMap) throws IOException {
HttpServletResponse response = ServletActionContext.getResponse();
String eventId = "测试文档-" + dataMap.get("tasknum");
//Configuration用于读取ftl文件
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
//指定路径
String templateFolder = NotTrueWorkOrderDocAction.class.getClassLoader().getResource("../../").getPath() + "templates/";
configuration.setDirectoryForTemplateLoading(new File(templateFolder));
// 输出文档路径及名称
File outFile = new File(templateFolder + eventId + ".doc");
//以 utf-8 的编码读取ftl文件
Template t = null;
//自己生成的ftl文件
t = configuration.getTemplate("nottrueworkorder.ftl", "utf-8");
Writer out = null;
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
try {
t.process(dataMap, out);
} catch (TemplateException e) {
e.printStackTrace();
}
out.close();
InputStream fin = null;
ServletOutputStream download = null;
try {
fin = new FileInputStream(outFile);
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
// 设置浏览器以下载的方式处理该文件名
String FileName = eventId + ".doc";
response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(FileName, "UTF-8"))));
download = response.getOutputStream();
IOUtils.copy(fin, download);
download.flush();
fin.close();
} finally {
if (fin != null) {
fin.close();
if (download != null) {
download.close();
}
if (outFile != null) {
outFile.delete(); // 删除临时文件
}
}
}
}