java使用freemaker下载word的流程如下:
1.新建一个word模板
2.另存为xml格式
3.将xml后缀的文件后缀改成.ftl
4.将ftl中需要替换的内容使用freemaker jstl语法进行替换
5.使用如下代码进行下载 注意:后缀一定得是.doc
public static File createWord(HttpServletResponse response,Map dataMap,String templateName,File outFile){
File directory = new File("");
String templateFolder = directory.getAbsolutePath();
try {
//创建配置实例
Configuration configuration = new Configuration();
//设置编码
configuration.setDefaultEncoding("UTF-8");
configuration.setEncoding(Locale.getDefault(), "utf-8");
try {
configuration.setDirectoryForTemplateLoading(new File(templateFolder+"\\template\\"));
} catch (IOException e) {
e.printStackTrace();
}
//获取模板
Template template = configuration.getTemplate(templateName);
//将模板和数据模型合并生成文件
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
//生成文件
template.process(dataMap, out);
//关闭流
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return outFile;
}
使用以上逻辑已经可以满足项目正常需求,但是做移动端应用的时候发现手机移动端的office无法打开通过freemaker下载的word,而且有时直接显示的是xml字符串。
网上的解决方案要么版本不兼容,要么提示无法打开xml格式的文件,最终还是考虑使用windows指令将doc文件另存一下的方案,就选中了jacob插件,这也是jacob只能在windows上运行的原因。
为了使用该功能,网上下载了三个版本的jacob插件,最终测试后发现1.19版本可以正常使用,具体附件可以去我的资源里面查找。
文件结构如下:
使用方法是:
1.将jacob-1.10-x64.dll放入到jdk/bin目录下面,不要听网上的放到jre下面(当然开发环境是jdk,生产环境是jre,如果你是生产环境还是要放到jre下面的)
2.将jacob.jar注入到项目里面,因为我是springboot项目,所以我一般这么处理:
2.1将jacob.jar注册到我本地仓库内
mvn install:install-file -Dfile=E:\jacob.jar -DgroupId=com.jacob -DartifactId=jacob -Dversion=1.19 -Dpackaging=jar
2.2pom.xml引入依赖
<dependency>
<groupId>com.jacob</groupId>
<artifactId>jacob</artifactId>
<version>1.19</version>
</dependency>
3.写业务逻辑代码
public static File trans(File oldFile) {
File directory = new File("");
String templateFolder = directory.getAbsolutePath();
String newPath = templateFolder+"/temp/"+UUID.randomUUID().toString()+".doc";
ActiveXComponent _app = new ActiveXComponent("KWPS.Application");
_app.setProperty("Visible", com.jacob.com.Variant.VT_FALSE);
Dispatch documents = _app.getProperty("Documents").toDispatch();
// 打开FreeMarker生成的Word文档
Dispatch doc = Dispatch.call(documents, "Open", oldFile.getPath(), com.jacob.com.Variant.VT_FALSE, com.jacob.com.Variant.VT_TRUE).toDispatch();
// 另存为新的Word文档
Dispatch.call(doc, "SaveAs",newPath, com.jacob.com.Variant.VT_FALSE, com.jacob.com.Variant.VT_TRUE);
Dispatch.call(doc, "Close", com.jacob.com.Variant.VT_FALSE);
_app.invoke("Quit", new com.jacob.com.Variant[] {});
ComThread.Release();
return new File(newPath);
}
4.修改里面的一些细节,比如,我本地用的是wps所以我引用的是KWPS.Application,如果你使用的是office,那么相应的改为Word.Application。