public Object createWord() {
String netPath = "";
String fileFullPath = null;
//Configuration实例化
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
Map<String, Object> dataMap = new HashMap<String, Object>();
getData(dataMap);
configuration.setClassForTemplateLoading(this.getClass(), "/cn/com/liandisys/policy/common/util/template");//模板文件所在路径
Template t = null;
try {
t = configuration.getTemplate("Report.ftl"); //获取模板文件
} catch (IOException e) {
e.printStackTrace();
}
//导出文件
long timeSpan = new Date().getTime();
String fileName = timeSpan + ".doc";
fileFullPath = this.getFileGeneratePath() + FILESEPARATOR + fileName;
File file = new File(fileFullPath);
Writer out = null;
try {
try {
netPath = commonService.exportWordFile();
} catch (Exception e) {
e.printStackTrace();
netPath = "{\"path\":\"\"}";
}
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
t.process(dataMap, out); //将填充数据填入模板文件并输出到目标文件
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "{\"path\":\"" + netPath + "\"}";
}
private static final String FILETYPE_WORDSUFFIX = ".doc";
//传递参数
private void getData(Map<String, Object> dataMap) {
String param1 = " 参数一 ";
String param2 = " 参数二 ";
... 参数有几个就创建几个
dataMap.put("param1", param1);
dataMap.put("param2", param2);
... 参数有几个就添加几个
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
for (int i = 0; i < list.size(); i++) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("number", i);
map.put("content", "内容"+i);
list.add(map);
dataMap.put("list", list);
}
}
private static final String FILESEPARATOR = System.getProperty("file.separator");
//导出word
public String exportWordFile() {
String netPath = "";
String fileFullPath = null;
long timeSpan = new Date().getTime();
String fileName = timeSpan + FILETYPE_WORDSUFFIX;
fileFullPath = this.getFileGeneratePath() + FILESEPARATOR + fileName;
ServletContext ctx = ContextLoader.getCurrentWebApplicationContext().getServletContext();
netPath = ctx.getContextPath() + "/fileDownload.do?name=" + timeSpan + "&suffix=" + FILETYPE_WORDSUFFIX;
File file = new File(fileFullPath);
file.getParentFile().mkdirs();
try {
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
}
return netPath;
}