A-A+
生成Word(Java-Beetl)
上篇文章介绍了基于FreeMaker生成Word文档,本篇会介绍如何基于Beetl生成Word文档。其实原理都是大同小异,先制作一个符合需求的Word文件,然后将此文件另存为xml格式,再将其中需要动态填充的内容使用模板引擎的占位符替换,最后用模板引擎重新渲染该xml文件,最后输出为.doc文件。
首先,需要引进Beetl模板引擎:
- <!--beetl start-->
- <dependency>
- <groupId>com.ibeetl</groupId>
- <artifactId>beetl</artifactId>
- <version>2.7.13</version>
- </dependency>
- <!--beetl end-->
然后,和上篇文章一样,使用占位符替换需要动态填充的字符。
接着,是一段完整的代码,展示了如何生成模板对象以及如何使用模板对象重新渲染模板文件并输出:
- public class BTLExportWord implements IExportWord{
- private static Template t;
- private Template createGroupTemplate() throws IOException {
- ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader(ConfigConst.TEMPLATE_PACK);
- Configuration config = Configuration.defaultConfiguration();
- GroupTemplate groupTemplate = new GroupTemplate(resourceLoader, config);
- Template template = groupTemplate.getTemplate(ConfigConst.BTL_TEMPLATE_TEST);
- t = template;
- return template;
- }
- public void exportWord(String outPath, Map<String, Object> dataMap) throws Exception {
- if (null == t){
- createGroupTemplate();
- }
- File outFile = new File(outPath);
- if (!outFile.getParentFile().exists()){
- outFile.getParentFile().mkdirs();
- }
- FileOutputStream fos = new FileOutputStream(outFile);
- OutputStreamWriter oWriter = new OutputStreamWriter(fos,"utf-8");
- Writer out = new BufferedWriter(oWriter);
- t.binding(dataMap);
- t.renderTo(out);
- }
- }
其中:
- public class ConfigConst {
- public final static String TEMPLATE_PACK = "/com/xnck/demo/exportword/template";
- public final static String BTL_TEMPLATE_TEST = "/template-test.btl";
- public final static String FTL_TEMPLATE_TEST = "/template-test.ftl";
- }
调用的时候:
- Map<String, Object> data = new HashMap<String, Object>();
- data.put("text1", "1111111111111");
- new BTLExportWord().exportWord("C:\\temp\\test.doc", data);
这种方式生成的doc文件在ios端用浏览器无法下载,因为ios端safari浏览器默认是预览文档。会直接报错,这种文档用libreoffice打开也会报错。
移动端没试过,只在PC端测试过。