package test.word;
import java.awt.Desktop;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class Test {
/**
* 获取数据
* @return
* @throws Exception
*/
private static Map<String, Object> getData() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("userName", "admin");//对应模板中的${userName}
map.put("nowDate", new Date().toString());//对应模板中的${nowDate}
List<String[]> tablt1 = new ArrayList<String[]>();
tablt1.add(new String[]{"1","广州11","838973","--"});
tablt1.add(new String[]{"2","佛山11","115542","--"});
tablt1.add(new String[]{"3","合计","955845","--"});
map.put("table1", tablt1);//<#list table1 as object></#list>
//其他数据
return map;
}
public static void main(String[] args) throws Exception {
createWord(getData(), "test.ftl", "F:/test/", "test"+System.currentTimeMillis()+".doc");
}
/**
*
* @param dataMap 数据
* @param templateName 模板名称
* @param filePath 保存文件路劲
* @param fileName 保存文件名
*/
public static void createWord(Map<?, ?> dataMap, String templateName,
String filePath, String fileName) {
try {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
// ftl模板文件统一放至 test.ftl包下面
configuration.setClassForTemplateLoading(Test.class, "/test/word/");
// 获取模板
Template template = configuration.getTemplate(templateName);
File outFile = new File(filePath + File.separator + fileName);
if (!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdirs();
}
// 将模板和数据模型合并生成文件
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFile), "UTF-8"));
// 生成文件
template.process(dataMap, out);
out.flush();
out.close();
Desktop desktop = Desktop.getDesktop();
desktop.open(new File(filePath + File.separator + fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
}