美文网首页
FreeMaker自动生成word文档

FreeMaker自动生成word文档

作者: Allenlll | 来源:发表于2020-07-07 11:21 被阅读0次

一、下载FreeMaker

地址:https://freemarker.apache.org/freemarkerdownload.html

二、制作文档模板

  • 把写好的work文档另存为Word 2003 XML 文档(*.xml)
  • 把需要替换的文字替换成${content}
 <w:t>${content1}</w:t></w:r></w:p>
  • 把需要替换的图片Base64编码
 <w:binData w:name="wordml://02000001.jpg xml:space="preserve">${image1}</w:binData>

  • 列表替换
#list

三、构造替换数据

  • HashMap构造数据,key就是上面ftl模板文件中的替换文字
 Map<String, String> DataSources = new HashMap();
  • 得到图片的Base64数据
   public static String[] getImg(List<File> paths) throws Exception {
        int k = paths.size();
        String[] imgPBASE64 = new String[paths.size()];

        for(int i = 0; i < k; ++i) {
            File fileImage = new File(((File)paths.get(i)).getAbsolutePath());
            InputStream inputStream = new FileInputStream(fileImage);
            byte[] data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
            imgPBASE64[i] = new String(Base64.encodeBase64(data));
        }

        return imgPBASE64;
    }

FreeMaker加载模板生成Word文档

  • 加载模板方法setClassForTemplateLoading
    第一个参数是当前类,第二个参数是模板文件ftl所在完整包名
    比如OrderByTime类包名:bean。模板文件.ftl包名:bean。
    注意:一定要用eclipse开发,我用的androidStudio开发打包,ftl模板文件打不进去,加载模板文件加载不成功。
    public static void getResult(Map dataMap, String templateName, String filePath, String fileName) {
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("UTF-8");
            configuration.setClassForTemplateLoading(OrderProByTime.class, "/bean");
            Template template = configuration.getTemplate(templateName);
            File outFile = new File(filePath + File.separator + fileName);
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }

            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
            template.process(dataMap, out);
            out.flush();
            out.close();
        } catch (Exception var9) {
            var9.printStackTrace();
        }

    }

读写Excel

Apache POI

相关文章

网友评论

      本文标题:FreeMaker自动生成word文档

      本文链接:https://www.haomeiwen.com/subject/szwwqktx.html