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

                       

  • 相关阅读:
    MyBatis查询没有数据返回值为list还是null--------采坑
    Java弱引用WeakReference详细讲解
    idea debug调试详细教程
    [Docker]Dockerfile指令
    [Docker]Dockerfile定制容器
    [Docker]tomcat 404
    [Docker]容器操作
    [Docker]镜像操作
    [Docker]docker-ce安装
    [CentOS7]安装界面直接修改eth0
  • 原文地址:https://www.cnblogs.com/lzmrex/p/9771134.html
Copyright © 2011-2022 走看看