A-A+

生成Word(Java-Beetl)

2017年08月11日 技术 评论 2 条 阅读 5,774 次

上篇文章介绍了基于FreeMaker生成Word文档,本篇会介绍如何基于Beetl生成Word文档。其实原理都是大同小异,先制作一个符合需求的Word文件,然后将此文件另存为xml格式,再将其中需要动态填充的内容使用模板引擎的占位符替换,最后用模板引擎重新渲染该xml文件,最后输出为.doc文件。

首先,需要引进Beetl模板引擎:

  1. <!--beetl start-->
  2.       <dependency>
  3.           <groupId>com.ibeetl</groupId>
  4.           <artifactId>beetl</artifactId>
  5.           <version>2.7.13</version>
  6.       </dependency>
  7.       <!--beetl end-->

然后,和上篇文章一样,使用占位符替换需要动态填充的字符。

接着,是一段完整的代码,展示了如何生成模板对象以及如何使用模板对象重新渲染模板文件并输出:

  1. public class BTLExportWord implements IExportWord{
  2.     private static Template t;
  3.     private Template createGroupTemplate() throws IOException {
  4.         ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader(ConfigConst.TEMPLATE_PACK);
  5.         Configuration config = Configuration.defaultConfiguration();
  6.         GroupTemplate groupTemplate = new GroupTemplate(resourceLoader, config);
  7.         Template template = groupTemplate.getTemplate(ConfigConst.BTL_TEMPLATE_TEST);
  8.         t = template;
  9.         return template;
  10.     }
  11.     public void exportWord(String outPath, Map<String, Object> dataMap) throws Exception {
  12.         if (null == t){
  13.             createGroupTemplate();
  14.         }
  15.         File outFile = new File(outPath);
  16.         if (!outFile.getParentFile().exists()){
  17.             outFile.getParentFile().mkdirs();
  18.         }
  19.         FileOutputStream fos = new FileOutputStream(outFile);
  20.         OutputStreamWriter oWriter = new OutputStreamWriter(fos,"utf-8");
  21.         Writer out = new BufferedWriter(oWriter);
  22.         t.binding(dataMap);
  23.         t.renderTo(out);
  24.     }
  25. }

其中:

  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 BTLExportWord().exportWord("C:\\temp\\test.doc", data);

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

标签:

2 条留言  访客:0 条  博主:0 条

  1. 哒哒哒

    这种方式生成的doc文件在ios端用浏览器无法下载,因为ios端safari浏览器默认是预览文档。会直接报错,这种文档用libreoffice打开也会报错。

    • 哼哼的泰迪熊

      移动端没试过,只在PC端测试过。

给我留言

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

用户登录

分享到: