在我们做jsp直接导出word文档时,往往需要基于一定的规则导出,如果这个规则或者格式是由word文档决定的,那么我们不妨采用freemarker(需下载freemarker-2.3.18.jar)来做这件事
1、首先需要做一个模板文件:我们需要一个word文档,这个文档包含一些已知数据,未知数据即变量用特殊标记标示(理论上标记随意取,后期在数据填充时需与此处的标记对应),然后另存为word XML文档格式(切记,另存为后需重新打开该文档,防止因为一些格式变化引起xml的变量与word中的不一致)。
2、其次需要一个工具类来处理由jsp到word文档(通过wordxml文档模板)的转换
代码大致功能如下
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class WordHandler {
private Configuration configuration = null;
public WordHandler() {
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
}
/**
*
* @author linds
* @date Jul 25, 2013
* @param templatePath
* @param templateName
* @return
* @throws IOException
* @Description TODO(获取模板)
*/
private Template getTemplate(String templatePath, String templateName) throws IOException {
configuration.setClassForTemplateLoading(this.getClass(), templatePath);
Template t = null;
t = configuration.getTemplate(templateName);
t.setEncoding("UTF-8");
return t;
}
/**
* @author linds
* @date Jul 25, 2013
* @param templatePath
* @param templateName
* @param dataMap
* @param out
* @throws Exception
* @Description TODO(根据模板填充数据)
*/
public void write(String templatePath, String templateName, Map dataMap, Writer out) throws Exception {
try {
Template t = getTemplate(templatePath, templateName);
t.process(dataMap, out);
} catch (IOException e) {
//e.printStackTrace();
System.out.println("WordHandler export word cancelled");
}finally {
try {
out.close();
}catch(IOException e){
}
}
}
}
3、最好就是基于模板填充数据即调用工具类导出word文档
方法大致如下:
public void download(){
Map<String, String> map=getWordData(); //该方法是获取业务数据的方法
String ajtitle=map.get("ajtitle");
WordHandler handler = new WordHandler();
try {
ServletOutputStream output = this.getResponse().getOutputStream();
String filename = ajtitle+".doc";
filename=filename.trim();
//String filename = "caseinfo-download.doc";
//判断浏览器
String userAgent = this.getRequest().getHeader("User-Agent");
boolean isIE = false;
if(userAgent.indexOf("MSIE") > 0){
isIE = true;
}
if(isIE){
filename = new String(filename.getBytes("GB2312"), "ISO-8859-1");
}else{
filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
}
//filename = new String(filename.getBytes("GB2312"), "ISO-8859-1");//linux平台需测试GB2312暂时屏蔽
this.getResponse().reset();
this.getResponse().setHeader("Content-disposition","attachment;filename=" + filename);
this.getResponse().setContentType("application/msword");
Writer out = new OutputStreamWriter(output, "UTF-8");
handler.write("/com/*/util", "templeate.xml",map,out);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
4、测试成功