zoukankan      html  css  js  c++  java
  • 使用FreeMarker生成word文档

    生成word文档的框架比较多,比如poi,java2word,itext和freemarker。 调研之后,freemarker来实现挺简单的,具体步骤如下:

    1. 新建word文档,占位符用${},比如:${name}。样例:

    你好 ${name}

    2. 把word另存为xml文件,如:example.xml

    3. 修改文件格式,把example.xml改为example.ftl. 

    4.安装notePad++ xml tools插件,用来打开example.ftl文件。里面可能有些文件分成了好几行,需要合并成一行,适当调整。

    5. 用freemarker解析ftl文件,并填充占位符:

    public static byte[] generateWord() {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
        configuration.setDefaultEncoding(UTF8);
        configuration.setClassForTemplateLoading(WordUtil.class, "/templates-path/"); //模板文件的路径
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
          Template template = configuration.getTemplate("example.ftl", UTF8);
          Writer writer = new BufferedWriter(new OutputStreamWriter(out, UTF8));
        Map<String, Object> dataMap = new HashMap<String,Object>();
        dataMap.put("name","jacky");

    template.process(dataMap, writer);
        } catch (TemplateException | IOException e) {
          log.error(e.getMessage(), e);
        }
        return out.toByteArray();
      }

                       

  • 相关阅读:
    POJ 1003 解题报告
    POJ 1004 解题报告
    POJ-1002 解题报告
    vi--文本编辑常用快捷键之光标移动
    常用图表工具
    September 05th 2017 Week 36th Tuesday
    September 04th 2017 Week 36th Monday
    September 03rd 2017 Week 36th Sunday
    September 02nd 2017 Week 35th Saturday
    September 01st 2017 Week 35th Friday
  • 原文地址:https://www.cnblogs.com/lzmrex/p/9771134.html
Copyright © 2011-2022 走看看