最近在开发一个功能,就是通过JAVA生成word文档,调研了很多开源框架,最终决定通过freemarker实现。具体实现方式如下:
先用word做个模板出来,然后保存为XML形式,再将需要替换的地方更换为freemarker标签,然后在JAVA中将模板读入在写出。
调试的时候,是用main方法弄的,没有任何问题,生成的word文档打开正常。
问题就出在将代码通过web形式调用时,JSP上点击按钮,然后调用代码,最后生成的word文档提示无法打开,系统无异常。
请问问题可能会出在哪块?
一下是部分代码:
public class DocumentHandler {
public static void createDoc(Map dataMap, String templateName, String wordPathName) {
Writer out = null;
try {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
System.out.println(configuration.getDefaultEncoding());
configuration.setClassForTemplateLoading(DocumentHandler.class, ResourcesUtil.getProperties(Constants.TEMPLATE_PATH));
// 加载模板
Template template = configuration.getTemplate(templateName);
File outFile = new File(wordPathName);
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
template.process(dataMap, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
调用方法:
Map dataMap = new HashMap();
dataMap.put("aaa", 111);
dataMap.put("bbb", "ddd");
dataMap.put("ccc", 33);
createDoc(dataMap, "test.ftl", "d:\\test.doc");