使用freemarker生成word文档

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

主要分三步: java

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

新建一个word文档。

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

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

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

使用freemarker生成word文档

生成模板

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

使用freemarker生成word文档

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

使用freemarker生成word文档

改为: code


使用freemarker生成word文档

注意编辑工具的字符集必定要和XML字符集一致,不然会形成乱码。 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 }
复制代码

测试代码: htm

复制代码
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 //其余内容相同

测试结果:

使用freemarker生成word文档
内容被替换,格式保持无缺。图片正常。