前言:
最近接手一个功能,要求是按照填写的内容将该部分导出word,内容展示如图所示。
背景:
之前写过导出word的功能,使用的是spire.doc的。第一次导出与预期不符,许多文本格式错乱,后采用前端富文本格式将参数全部保留,后端对导出进行处理。百度了很多spire.doc导出的方法,使用了doc转mht,再转ftl制作模板文件(如何制作模板文件详见方法内)。成功解决富文本导出word问题。但是在实际使用中发现,客户使用的是特制版的wps,然后wps打开word制成的模板文件生成的doc文档是会出现问题的。这就让人很无语了。当时以为事情很简单,只需要使用wps重新制作一个模板。但是后面还是年轻了,首先wps的mht文件不存在content-Location files.file。这就导致了无法定位到该模板文件。后续也就无法生成文件了。这个问题困扰了我三天(当然,这三天也还有其他活干),第三天晚上让我成功找到一种方法-直接使用apache的poiti-tl,使html直接转为文件。将word导出的三个具体方法写下。
spire.doc方法:
普通doc文档,不带富文本
模板制作:doc制作,将要替换的文本内容使用占位符
20221205_111036
private File createWord(UgiGfWarningNotices notice, String templateName, String filePath) {
//创建文件
String name = "供电公司供电服务预警督办通知单" + notice.getNoticeId() + ".doc";
File file1 = new File(filePath + "/" + templateName + name);
try {
// 创建配置实例
Configuration configuration = new Configuration(new Version("2.3.0"));
// 设置utf-8编码
configuration.setDefaultEncoding("utf-8");
//设置处理空值
configuration.setClassicCompatible(true);
//设置加载ftl模版加载方式 分为两种加载方式:类加载以及绝对路径加载。类加载优点方便找到模板,缺点是打成jar包基本找不到
//绝对路径加载优点:打成jar包也能找到模板,缺点就是容易丢失
//类加载
configuration.setClassForTemplateLoading(WordUtils.class, "/templates/template3");
//绝对路径加载
//configuration.setDirectoryForTemplateLoading(new File("D:\\opt\\"));
//指定ftl文件的路径,根据父目录进行指定
// 判断父路径是否存在
if (!file1.getParentFile().exists()) {
// 不存在自动创建
file1.getParentFile().mkdirs();
}
//将模板和数据模型合并生成文件
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file1), "utf-8"));
//获取模板
Template template = configuration.getTemplate(templateName + ".ftl");
//生成文件
HashMap<String, Object> map = new HashMap<>();
map.put("noticeId", notice.getNoticeId());
map.put("sendDept", notice.getSendDept());
map.put("signDate", notice.getSignDate());
map.put("ponsorDepartment", notice.getSponsorDepartment());
map.put("orderNo", notice.getOrderNo());
map.put("cooDepartment", notice.getCooperativeDepartment());
map.put("noticeTitle", notice.getNoticeTitle());
map.put("content", notice.getContent());
map.put("reason", notice.getReason());
template.process(map, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file1;
}
富文本导出word:
模板制作视频:
20221205_111514
html制作:
做好模板后直接另存为html页面即可,具体参照代码。
代码地址:https://gitee.com/jacklyxiaojie/html_to_word.git