private static final String templateFolder = AqmisFileUtil.class.getClassLoader().getResource("../../").getPath()+"/WEB-INF/classes/template/";
public static void createDoc(HttpServletRequest request, HttpServletResponse response,String templatUrl,String templatName,Map root){
//获取ftl模板的路径
String substring = templateFolder.substring(1);
//Configuration用于读取ftl文件
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
try {
//读取模板
configuration.setDirectoryForTemplateLoading(new File(substring));
Template t = configuration.getTemplate(templatUrl);
//导出临时文件的名称路径
String name = templatName +".doc";
String outFile ="D:/"+name;
// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
try {
//执行生产临时文件
t.process(root, out);
} catch (TemplateException e1) {
e1.printStackTrace();
}
out.flush();
out.close();
InputStream fis = null;
OutputStream toClient = null;
try {
//读取临时文件
fis = new BufferedInputStream(new FileInputStream(outFile));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
String fileName = StringUtil.encodingString(name, "GB2312", "ISO-8859-1"); //这里要用URLEncoder转下才能正确显示中文名称
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Content-Length", "" + buffer.length);
toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
//删除临时文件
File tempFile =new File(outFile);
if(tempFile.exists()){
tempFile.delete();
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(fis!=null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(toClient!=null){
toClient.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
java实现freemarker导出word
猜你喜欢
转载自blog.csdn.net/shiboyuan0410/article/details/79915175
今日推荐
周排行