zoukankan      html  css  js  c++  java
  • 使用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/
  • 相关阅读:
    DataGridViewer表格中设置ProgressBar显示进度百分比和修改进度条颜色
    excel操作
    sql的时间
    DateTime的各种用法
    DataGridViewer表格中将Button设置为不可用
    OpenCV特征检测和特征匹配
    切片
    c#命名规范
    Remove Linked List Elements
    Remove Nth Node From End of List
  • 原文地址:https://www.cnblogs.com/lichmama/p/6652161.html
Copyright © 2011-2022 走看看