使用freemarker将xml模板填充数据后转换为word

package com.qlyl.util;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
 
public class XmlToWord {
	
    private static Configuration configuration = null;
    
    public static void main(String[] args) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		//填充数据
        map.put("custname", "崔超群");
        map.put("highJ", "1");
        Map<String, String> dataMap = new HashMap<String, String>();
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        dataMap.put("collectTime", "2020-01-19");
        list.add(dataMap);
        dataMap = new HashMap<String, String>();
        dataMap.put("collectTime", "2020-01-20");
        list.add(dataMap);
        map.put("timeList", list);
		exportMillCertificateWord(map, "D:\\word报告模板\\", "testFtl.xml", "D:\\word报告模板\\testXml2Word.docx");
	}
 
    @SuppressWarnings("deprecation")
	public static void exportMillCertificateWord(Map<?, ?> map, String templateFolder, String template, String name) throws IOException {  
    	configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateFolder));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Template freemarkerTemplate = configuration.getTemplate(template);
        // 调用工具类的createDoc方法生成Word文档 
        createDoc(map, freemarkerTemplate, name); 
    }
 
    private static File createDoc(Map<?, ?> dataMap, Template template, String name) {
        File f = new File(name);
        Template t = template;
        try {
        	f.createNewFile();
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) { 
            ex.printStackTrace(); 
            throw new RuntimeException(ex); 
        }
        return f;  
    }
 
}
发布了6 篇原创文章 · 获赞 0 · 访问量 94
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览