package com.ry.project.util.commUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.*;
import java.util.Map;
public class WordUtil {
private Configuration configuration = null;
public WordUtil() {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}
//指定下载路径
public void createDoc(Map dataMap, String fileName) throws UnsupportedEncodingException {
configuration.setClassForTemplateLoading(this.getClass(), "/");
Template doct = null;
try {
doct = configuration.getTemplate("infoModel.ftl", "utf-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File outfile = new File(fileName);
Writer out = null;
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(outfile);
OutputStreamWriter oWriter = new OutputStreamWriter(outputStream, "UTF-8");
out = new BufferedWriter(oWriter);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
doct.process(dataMap, out);
out.close();
outputStream.close();
} catch (TemplateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//不指定下载路径,,,默认浏览器下载,需要在代码中设置请求头
public void createDoc(Map dataMap, OutputStream outfil) throws UnsupportedEncodingException {
configuration.setClassForTemplateLoading(this.getClass(), "/");
System.out.println(">>>>>class:" + this.getClass());
Template doct = null;
try {
doct = configuration.getTemplate("model.ftl", "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
Writer out = null;
OutputStreamWriter oWriter = new OutputStreamWriter(outfil, "UTF-8");
out = new BufferedWriter(oWriter);
try {
doct.process(dataMap, out);
System.out.println("《《《《《《《《下载结束》》》》》");
out.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
response.reset();//清除空白行纺织报错
response.setHeader("Access-Control-Allow-Origin", "*");//所有域都可以跨
response.setHeader("Content-Type", "application/octet-stream;charset=UTF-8");//二进制 流文件
response.setHeader("Content-Disposition", "attachment;filename=" + endCodeFileName+".doc");//下载及其文件名
response.setHeader("Connection", "close");//关闭请求头连接
//设置文件在浏览器打开还是下载
response.setContentType("application/x-download");
}