使用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;  
    }
 
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值