1. 程式人生 > >word文件從伺服器匯出(用freemarker模板匯出)

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;
	}
}