使用freemarker生成word文档

项目有时候需要将一些内容导出成word格式,实现方式很多种,如:POI导出,freemarker导出。freemarker导出比较简单。

主要分三步:

  1. 新建一个word文档
  2. 生成模板
  3. 动态生成word。

新建一个word文档。

新建一个word文档,把格式和内容定好。如下图:导出内容和导出人两部分,到时候会根据运行时内容替换。

为了方便修改模板,建议写一些文字,否则修改模板的时候,不知道在哪改。

最好不要直接写freemarker标记。word有可能会将${marker}这几个字符分开存储。

生成模板

将填好的模板,保存成xml格式。

用xml编辑工具,记事本即可。将里面导出内容和导出人这两个动态内容换成freemarker模板语言。

改成:

注意编辑工具的字符集一定要和XML字符集一致,否则会造成乱码。

动态生成word内容

java代码:

 1 public class WordHandler {
 2     private Configuration configuration = null;
 3     Log logger = LogFactory.getLog(WordHandler.class);
 4 
 5     public WordHandler() {
 6         configuration = new Configuration();
 7         configuration.setDefaultEncoding("UTF-8");
 8     }
 9     
10     private Template getTemplate(String templatePath, String templateName) throws IOException {
11         configuration.setClassForTemplateLoading(this.getClass(), templatePath);
12         Template t = null;
13         t = configuration.getTemplate(templateName);
14         t.setEncoding("UTF-8");
15         return t;
16     }
17 
18     
19     public void write(String templatePath, String templateName, Map dataMap, Writer out) throws WordHandlerException {
20         try {
21             Template t = getTemplate(templatePath, templateName);
22             t.process(dataMap, out);
23         } catch (IOException e) {
24             logger.error(e);
25             throw new WordHandlerException(e);
26         } catch (TemplateException e) {
27             logger.error(e);
28             throw new WordHandlerException(e);
29         } finally {
30             try {
31                 out.close();
32             } catch (IOException e) {
33                 logger.error(e);
34                 throw new WordHandlerException(e);
35             }
36         }
37     }
38 }

测试代码:

1         Map map = new HashMap();
2         map.put("content","这是基于freemarker导出成word格式。包含图片");
3         map.put("userName","二土");
4         WordHandler handler = new WordHandler();
5         Writer out = new OutputStreamWriter(new FileOutputStream("D:\\uploadFiles\\测试.doc"), "UTF-8");
6         handler.write("/test/com/sinoprof/tiger/doc", "test.xml", map, out);
7     

为了保证生成的正确性,输出流一定要设字符集。

上表的测试代码是生成本地文件。如果是基于servlet的导出,如下表:

1 ServletOutputStream out = res.getOutputStream();
2 Writer writer = new OutputStreamWriter(out, "UTF-8");
3 //其他内容相同

测试结果:

内容被替换,格式保持完好。图片正常。

posted @ 2013-05-26 11:25  二土  阅读(657)  评论(1)    收藏  举报