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();
      }

                       

  • 相关阅读:
    静静的看twittervision
    MSSQL中的随机函数
    紧张非封闭式开发中
    be my friend
    这个五一
    检讨
    SilverLight,有多少人关心呢?
    并查集模板题P3367 【模板】并查集
    并查集简单介绍
    约数之和模板题
  • 原文地址:https://www.cnblogs.com/lzmrex/p/9771134.html
Copyright © 2011-2022 走看看