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

之前写过一篇,用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;
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值