导出生成word
阅读原文时间:2023年07月09日阅读:1

用XML做就很简单了。Word从2003开始支持XML格式,大致的思路是先用office2003或者2007编辑好word的样式,然后另存为xml,将xml翻译为FreeMarker模板(后缀为.ftl),

最后用java来解析FreeMarker模板并输出Doc。经测试这样方式生成的word文档完全符合office标准,样式、内容控制非常便利,打印也不会变形,生成的文档和office中编辑文档完全一样。

然后将word另存为.xml文件,打开文件,找到title将其修改为${title},后面要替换的内容依次替换掉。然后将.xml文件后缀改为.ftl,导入.ftl模板文件到指定目录。加载jar包freemarker.jar

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

public class test {
/**
* 导出生成word
*/
@RequestMapping("exportWord")
public void exportword(HttpServletRequest request, HttpServletResponse response, @RequestParam MapparamMap) throws Exception{
File file = null;
Map result = gzpService.getWordData(paramMap);
String fileName = "电力监控工作票.doc";
try{
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
response.setHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("GBK"),"ISO-8859-1"));
exportWord(response.getOutputStream(),"gzo.ftl",result);
}catch (Exception e){
e.printStackTrace();
response.reset();
response.setContentType("text/html; charset=UTF-8");
String s = "";
response.getOutputStream().print(s);
}finally {
response.flushBuffer();
}
}

/\*\*  
 \* 导出word临时文件  
 \*/  
private void exportWord(ServletOutputStream sos, String model, Map<String,Object> dataMap){  
    Configuration configuration =new Configuration();  
    configuration.setDefaultEncoding("UTF-8");  
    configuration.setEncoding(Locale.getDefault(),"UTF-8");  
    try{  
        configuration.setClassForTemplateLoading(this.getClass(),"/template");//模板的路径  
        configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(),"/template"));  
        Template t = configuration.getTemplate(model,"UTF-8");  
        Writer out = new OutputStreamWriter(sos,"UTF-8");  
        t.process(dataMap,out);  
        out.close();  
        sos.close();  
    }catch (Exception e){  
        e.printStackTrace();  
    }  
}  

}
修改.ftl文件,找到列表所在位置,将其要加入的列表加入到文件中。在列表前加入<#list list as l>(在它的头上加一个<#list 你的集合名称 as xxxx>), 并在结尾加上。修改list内容,在要输出的名字前面加上l.。如xuehao,修改为l.xuehao。这样有点像EL表达式的使用。