您的位置:首页 > 编程语言 > Java开发

word文档从服务器导出(用freemarker模板导出)

2017-04-10 15:27 281 查看

之前写过一篇,用Java编写生成word文档,动态添加数据到word文档buguo

http://blog.csdn.net/u012438476/article/details/64443535

该方法适合小的java程序,当用到javaWeb时发现导出的word在服务器上,而不是下载到客户端,接下来这篇文章是写从服务器上下载文件到本地,下载时浏览器弹出下载框,乱码在代码里已处理。注意,不要用ajax传参,因为ajax只能处理文本信息,不能处理二进制信息。

具体代码如下:

DocumentHandler.java//生成word文档

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class DocumentHandler {
private Configuration configuration = null;

public DocumentHandler() {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}

public void createDoc(Map<String, Object> dataMap, String fileName, String tempName, String realPath)
throws UnsupportedEncodingException {
// dataMap 要填入模本的数据文件
// 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
// 这里的模板是放在template包下面
configuration.setClassForTemplateLoading(this.getClass(), "/com/wondersgroup/esfimpl/fjgs/file");
Template t = null;
try {
// test.ftl为要装载的模板
t = configuration.getTemplate(tempName);
} catch (IOException e) {
e.printStackTrace();
}
// 输出文档路径及名称
File outFile = new File(realPath + fileName);
Writer out = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outFile);
OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");
// 这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。
// out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(oWriter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}

try {
t.process(dataMap, out);
out.close();
fos.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}DownloadWord.java//下载文件到客户端
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadWord {
public static void download(HttpServletRequest request,
HttpServletResponse response, String fileUrl, String fileName) {
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
try {
// 客户使用保存文件的对话框:
fileUrl = fileUrl + fileName;
//fileUrl = new String((fileUrl + fileName).getBytes("utf-8"), "utf-8");
//String userAgent = request.getHeader("User-Agent");
//byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8");// fileName.getBytes("UTF-8")处理safari的乱码问题
//fileName = new String(bytes, "ISO-8859-1");// 各浏览器基本都支持ISO编码

response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
// 通知客户文件的MIME类型:
bis = new java.io.BufferedInputStream(new java.io.FileInputStream((fileUrl)));
bos = new java.io.BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
int i = 0;

while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
i++;
}
bos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bis = null;
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bos = null;
}
}
}
}

controller.java//控制层调用
public void saveTemplatePersonnelYear(HttpServletRequest request,
HttpServletResponse response) throws Exception {
try {
Map map = new HashMap<String, Object>();
map.put("entryPerson", new String(request.getParameter("entryPerson").getBytes("iso-8859-1"), "utf-8"));
map.put("sex", new String(request.getParameter("sex").getBytes("iso-8859-1"), "utf-8"));
map.put("birthday",new String(request.getParameter("birthday").getBytes("iso-8859-1"), "utf-8"));
map.put("work", new String(request.getParameter("work").getBytes("iso-8859-1"), "utf-8"));
map.put("selfEvalution", new String(request.getParameter("selfEvalution").getBytes("iso-8859-1"), "utf-8"));

DocumentHandler mdoc = new DocumentHandler ();
String Docname = "年度考核.doc";
String folderName = "word";
String realPath = request.getSession().getServletContext().getRealPath("/")+"/WEB-INF/"+folderName+"/";
mdoc.createDoc(map, Docname,"年度考核模板.ftl",realPath);//数据,生成文件名,模板名(模板怎么写在上一篇文章),路径
DownloadWord.download(request, response, realPath,Docname);
} catch (Exception e) {
e.printStackTrace();
}
}

页面
function downloadTemplate(){;
var entryPerson = $("#entryPerson").val();
var sex = $("#sex").val();
var birthday = $("#birthday").val();
var work = $("#work").val();
var selfEvalution = $("#selfEvalution").val();
if(entryPerson =="" || entryPerson ==null){
alert("请填写录入人");
}else{
var url = "<%=ApplicationContextUtil.getBasePath(request)%>template/save_template_personnel_year.do?entryPerson="+entryPerson+"&sex="+sex+"&birthday="+birthday+"&work="+work+"&selfEvalution="+selfEvalution;
location.href=url;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java word