java通过解析ftl文件动态生成word。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class ExportWord {
/**
* 导出Word文档公用方法
* @param templateName 模板名称
* @param configuration 配置信息
* @param fileName 文件名称
* @param dataMap 模板加载数据
* @param downloadFileName 浏览器下载文件的名称
* @param response
* @throws Exception
*/
public static void exportWord(String templateName,Configuration configuration,String fileName,Map<Object,Object> dataMap,String downloadFileName,HttpServletResponse response)
throws Exception{
configuration.setDefaultEncoding("utf-8");
Template t = null;
t = configuration.getTemplate(templateName);
File file=new File("E:/temp");
if(!file.exists()){
file.mkdirs();
}
StringBuffer sb = new StringBuffer(fileName);
fileName = sb.toString();
if(sb.length()>80){
fileName = sb.toString().replace("\\","")
.replace("/", "")
.replace("*", "")
.replace("?", "")
.replace("<", "")
.replace(">", "")
.replace("|", "");
fileName = sb.substring(0, 80);//word文档128个字长度算越界
}
if(fileName.length()<3)
{
fileName += "xxx";
}
File outFile = file.createTempFile(fileName.toString(), ".doc", file);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
t.process(dataMap, out);
InputStream is = new FileInputStream(outFile);
response.reset();
response.setContentType("application/vnd.ms-word;charset=UTF-8");
response.addHeader("Content-Disposition","attachment; filename=\"" +URLEncoder.encode(downloadFileName+".doc", "UTF-8")+ "\"");
byte[] b = new byte[1024];
int len;
while ((len=is.read(b)) >0) {
response.getOutputStream().write(b,0,len);
}
is.close();
response.getOutputStream().flush();
response.getOutputStream().close();
}
}