• 使用freemarker模板生成word文档


    项目中最近用到这个东西,做下记录。

    如下图,先准备好一个(office2003)word文档当做模板。文档中图片、姓名、性别和生日已经使用占位符代替,生成过程中将会根据实际情况进行替换。

    然后将word文档另存为“Word XML文档”

    使用xml编辑器打开test.xml,将下图中的BASE64字符串替换为${image},后面程序中将使用这个替换图片。

    完成后,将test.xml重命名为test.ftl。

    接下来,实现代码如下:

    public class ExportDoc {
        
        private Configuration configuration;
        private String encoding;
        
        public ExportDoc(String encoding) {
            this.encoding = encoding;
            configuration = new Configuration(Configuration.VERSION_2_3_22);
            configuration.setDefaultEncoding(encoding);
            configuration.setClassForTemplateLoading(this.getClass(), "/com/lichmama/test/templates");
        }
        
        public Template getTemplate(String name) throws Exception {
            return configuration.getTemplate(name);
        }
        
        public String getImageStr(String image) throws IOException {
            InputStream is = new FileInputStream(image);
            BASE64Encoder encoder = new BASE64Encoder();
            byte[] data = new byte[is.available()];
            is.read(data); is.close();
            return encoder.encode(data);
        }
        
        public Map<String, Object> getDataMap() {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("name", "lichmama");
            dataMap.put("gender", "男");
            dataMap.put("birthday", "19**年**月**日");
            try {
                dataMap.put("image", getImageStr("D:\头像.jpg"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return dataMap;
        }
        
        public void exportDoc(String doc, String name) throws Exception {
            Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(doc), encoding));
            getTemplate(name).process(getDataMap(), writer);
        }
        
        public static void main(String[] args) throws Exception {
            ExportDoc maker = new ExportDoc("UTF-8");
            maker.exportDoc("D:\test.doc", "test.ftl");
        }
    }

    生成的文档效果如下图:

    更新:

    此方案存在种种弊端,推荐大家使用pandoc、docverter或其他如poi的方式。

    // pandoc
    https://www.pandoc.org/
    
    // docverter(ruby)
    https://www.docverter.com/
  • 相关阅读:
    hadoop集群管理之 SecondaryNameNode和NameNode
    无法fsck问题解决
    处世
    [THUSC2016]成绩单
    Python安装官方whl包、tar.gz包、zip包
    poj1159 Palindrome 动态规划
    hoj1249 Optimal Array Multiplication Sequence 矩阵链乘
    hoj分类(转)
    hoj 2012 winter training Graph Day1 106 miles to Chicago图论最短路dijkstra算法
    poj1050 To the Max
  • 原文地址:https://www.cnblogs.com/lichmama/p/6652161.html
Copyright © 2020-2023  润新知