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;
}
}
使用freemarker将xml模板填充数据后转换为word
最新推荐文章于 2024-10-12 11:18:17 发布