A-A+

生成Word(Java-FreeMaker)

2017年08月11日 技术 暂无评论 阅读 2,427 次

生成Word将分成两篇文章介绍,原理大同小异,主要是使用的模板引擎有所不同,网络上比较多的是如何使用FreeMaker来生成,所以本篇还是基于FreeMaker来简单介绍一下,下一篇将基于Beetl来介绍。

首先,引入FreeMaker(基于Maven):

  1. <!--freemarker start -->
  2.   <dependency>
  3.       <groupId>org.freemarker</groupId>
  4.       <artifactId>freemarker</artifactId>
  5.       <version>2.3.23</version>
  6.   </dependency>
  7.   <!--freemarker end-->

然后使用将word文件(.doc或.docx)另存为xml文件,并将其中需要动态填充的内容使用FreeMaker的占位符号替换掉,如下:

  1. <w:r>
  2.     <w:rPr>
  3.         <w:rFonts w:hint="eastAsia"/>
  4.     </w:rPr>
  5.     <w:t>${text1}</w:t>
  6. </w:r>

然后是一段完整的代码:

  1. public class FTLExportWord implements IExportWord{
  2.     private static Template t;
  3.     private Configuration createConfig() throws IOException {
  4.         Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
  5.         configuration.setDefaultEncoding("UTF-8");
  6.         configuration.setClassForTemplateLoading(FTLExportWord.class, ConfigConst.TEMPLATE_PACK);
  7.         configuration.setClassicCompatible(true);
  8.         return configuration;
  9.     }
  10.     private Template createTemplate() throws IOException {
  11.         Configuration configuration = createConfig();
  12.         Template template = configuration.getTemplate(ConfigConst.FTL_TEMPLATE_TEST);
  13.         t = template;
  14.         return t;
  15.     }
  16.     public void exportWord(String outPath, Map<String, Object> dataMap) throws Exception {
  17.         if (null == t){
  18.             createTemplate();
  19.         }
  20.         File outFile = new File(outPath);
  21.         if (!outFile.getParentFile().exists()){
  22.             outFile.getParentFile().mkdirs();
  23.         }
  24.         FileOutputStream fos = new FileOutputStream(outFile);
  25.         OutputStreamWriter oWriter = new OutputStreamWriter(fos,"utf-8");
  26.         Writer out = new BufferedWriter(oWriter);
  27.         t.process(dataMap, out);
  28.     }
  29. }

其中:

  1. public class ConfigConst {
  2.     public final static String TEMPLATE_PACK = "/com/xnck/demo/exportword/template";
  3.     public final static String BTL_TEMPLATE_TEST = "/template-test.btl";
  4.     public final static String FTL_TEMPLATE_TEST = "/template-test.ftl";
  5. }

调用的时候:

  1. Map<String, Object> data = new HashMap<String, Object>();
  2. data.put("text1""1111111111111");
  3. new FTLExportWord().exportWord("C:\\temp\\test.doc", data);

完整代码在这里:https://gitee.com/blackzs/exportword

给我留言

Copyright © 字痕随行 保留所有权利.   Theme  Ality

用户登录

分享到: