freemaker导出word

1.首先将word里面需要改的数据写成这种形式
2.另存为xml格式
3.方法如下
  /**
  * 导出word
  * @param ddid
  * @return
  * @throws Exception
  */
 @RequestMapping("/cbTongjiDuty/do_export.htm")
 public void doexport(HttpServletRequest request, HttpServletResponse response, ModelMap map, Long id) throws Exception {
  FreemarkerExecutor exe = new FreemarkerExecutor();
  exe.setClassForTemplateLoading("/config/template"); //文件路径
  exe.setTemplate("秦皇岛海事局VTS值班业务工作统计表.xml"); //文件名称
  CbTongjiDuty cbTongjiDuty=cbTongjiBaobiaoManager.doGet(CbTongjiDuty.class, id);
  String fname = "VTS值班业务工作统计表"+".doc"; //导出后的文件名称
  map.put("duty", cbTongjiDuty); //传值
  response.setContentType("application/octet-stream");
  response.setHeader("Content-Disposition", "attachment;filename="
    +  new String(fname.getBytes("gb2312"), "ISO8859-1"));
  Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8")); //Writer继承java.io包
  exe.process(map, out);
 }
4. FreemarkerExecutor 类如下  
package com.util;
 
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
 
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
 
 
 
 
public class FreemarkerExecutor {
 
 private Configuration config;
 private Template template;
 
 public FreemarkerExecutor(){
  config = new Configuration();  
  config.setDefaultEncoding("utf-8");  
  config.setClassicCompatible(true);
 }
 
 /**
  * 设置模板存放目录
  * @param path
  */
 public void setClassForTemplateLoading(String path) {
  config.setClassForTemplateLoading(this.getClass(), path);
 }
 
 /**
  * 设置模板文件
  * @param fileName
  * @throws IOException
  */
 public void setTemplate(String fileName) throws IOException {
  template = config.getTemplate(fileName,"UTF-8");
  template.setOutputEncoding("UTF-8");
 }
 
 
 /**
  * 合并输出
  * @param data
  * @param out
  * @throws TemplateException
  * @throws IOException
  */
 public void process(Map<String, Object> data, Writer out) throws TemplateException, IOException {
  if (template == null) {
   throw new RuntimeException("please set the template");
  }
  template.process(data, out);
 
  out.flush();
  out.close();
 }
 
}

猜你喜欢

转载自2902702156.iteye.com/blog/2363729