使用freemarker生成word
注意事项:需要注意freemarker版本和excel版本的对应问题
以下使用的是:freemarker-2.3.20.jar和excel2007
模板开头:
模板创建方式:
将写好的模板保存为2003的xml格式,记住要选中仅保存数据
将xml模板文件后缀名改为.ftl
模板参考:
后台代码:
// @RequiresPermissions("manage:order:order:export")
@RequestMapping(value = "exportWord", method=RequestMethod.GET)
public String exportWord(Order order, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
try {
System.out.println("id=="+order.getId());
Order orderInfo = orderService.get(order);
System.out.println("billNo=="+order.getBillNo());
String fileName = "订单:"+orderInfo.getBillNo()+".doc";
Map<String,Object> dataMap = new HashMap<String,Object>();
dataMap.put("customPhone", orderInfo.getCustom().getPhone());
dataMap.put("personName", orderInfo.getCurPerson().getName());
dataMap.put("serveContent", orderInfo.getServeContent());
//-----
dataMap.put("cusName", orderInfo.getCustom().getName()!=null?orderInfo.getCustom().getName():"");
dataMap.put("cusIdCard", orderInfo.getCustom().getIdCard()!=null?orderInfo.getCustom().getIdCard():"");
dataMap.put("curPerIdCard", orderInfo.getCurPerson().getIdCard()!=null?orderInfo.getCurPerson().getIdCard():"");
dataMap.put("curPerPhone", orderInfo.getCurPerson().getPhone()!=null?orderInfo.getCurPerson().getPhone():"");
//-----
dataMap.put("serveAddr", orderInfo.getServeAddr()!=null?orderInfo.getServeAddr():"");
System.out.println(orderInfo.getStartTime());
System.out.println(orderInfo.getEndTime());
dataMap.put("startTime", new DateTime(orderInfo.getStartTime()).toString("yyyy-MM-dd")); //orderInfo.getStartTime()
dataMap.put("endTime",new DateTime(orderInfo.getEndTime()).toString("yyyy-MM-dd")); //orderInfo.getEndTime()
dataMap.put("monthSalary", orderInfo.getMonthSalary());
dataMap.put("manageFee", orderInfo.getManageFee());
dataMap.put("deposit", orderInfo.getDeposit());
dataMap.put("remarks", orderInfo.getRemarks()!=null?orderInfo.getRemarks():"");
new ExportWord("UTF-8").exportDoc(response, fileName, "orderTemplate.ftl", dataMap);
return null;
} catch (Exception e) {
addMessage(redirectAttributes, "导出订单失败!失败信息:"+e.getMessage());
return "redirect:"+Global.getAdminPath()+"/manage/order/order/?repage";
}
}
================================================================================================
package com.xxx.common.utils.word;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xxx.common.utils.Encodes;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class ExportWord {
private static Logger logger = LoggerFactory.getLogger(ExportWord.class);
private Configuration configuration;
private String encoding;
private String exportPath = "D:\\test\\";
/**
* 构造函数
* 配置模板路径
* @param encoding
*/
public ExportWord(String encoding){
this.encoding = encoding;
configuration = new Configuration();
configuration.setDefaultEncoding(encoding);
configuration.setClassForTemplateLoading(this.getClass(), "/wordtemplate");
}
/**
* 获取模板
* @param name
* @return
* @throws Exception
*/
public Template getTemplate(String name) throws Exception {
return configuration.getTemplate(name);
}
/**
* 导出word文档到指定目录
* @param doc
* @param name
* @throws Exception
*/
public void exportDocFile(String fileName, String tplName,Map<String, Object> data) throws Exception {
logger.debug("导出word到D:\test");
//如果目录不存在,则创建目录
File exportDirs = new File(exportPath);
if(!exportDirs.exists()){
exportDirs.mkdirs();
}
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath+fileName), encoding));
getTemplate(tplName).process(data, writer);
}
/**
* 导出word文档到客户端
* @param doc
* @param name
* @throws Exception
*/
public void exportDoc(HttpServletResponse response,String fileName,String tplName,Map<String, Object> data) throws Exception {
logger.debug("导出word客户端");
response.reset();
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
// 把本地文件发送给客户端
Writer out = response.getWriter();
getTemplate(tplName).process(data, out);
out.close();
}
}