前段时间,接到客户的需求,需要导出word满足日常需求。若采用excel直接生成的话难度有点大,我再网上也没有找到相
关的教程。所以我采用方案二:先事先编写好一个模板,通过系统运行产生生产数据,通过修改数据达到导出生成word的目的。
也希望为能解和我有相同需求的工友们的燃眉之急。
no more talks ,show your code!
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WordTest2 {
public static void main(String[] args) throws Exception {
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("pyear", "2017");
dataMap.put("pmonth", "04");
dataMap.put("sumcmdnum", "1234");
dataMap.put("sumhgrate", "34");
dataMap.put("sumhb", "12");
dataMap.put("sortgood4", "134");
dataMap.put("sortbad4", "34");
dataMap.put("goodone", "124");
dataMap.put("beforhgl", "4");
dataMap.put("afterhgl", "13");
List<Map<String, Object>> plantList = new ArrayList<Map<String, Object>>();
for (int i = 1; i <= 5; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("cmdnum", "1" + i);
map.put("plantname", "��ͨ" + i);
map.put("unitindex", "#" + i);
map.put("facgxdl", "fct" + i);
map.put("toygxdl", "toy" + i);
map.put("hgrate", "hgl" + i);
map.put("khmark", "khmark" + i);
map.put("bcmark", "bcmark" + i);
plantList.add(map);
}
dataMap.put("plantList", plantList);
// Configuration用于读取ftl文件
Configuration configuration = new Configuration(
Configuration.VERSION_2_3_22);
configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File(
"D://"));
// 输出文档路径及名称
File outFile = new File("D://test123324.doc");
// 以utf-8的编码读取ftl文件
Template t = configuration.getTemplate("abc.xml", "utf-8");
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFile), "utf-8"), 10240);
t.process(dataMap, out);
out.close();
}
}
需要先将需要导出的word模板写好,将后缀名改成.xml格式的(上述测试代码中的acb.xml)。
运行即可导出word文件。
测试文件,测试模板,测试代码我发到下面链接上了: