java使用poi或者jxl實現excel導出之後如何彈出保存提示框

無論使用poi還是使用jxl導出excel都需要用到流

一種是outputstrean,另一種fileoutputstream

第一種:如果想要彈出保存的提示框必須加入下列三句
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setHeader("Content-Disposition","attachment;filename="+filename);
response.setCharacterEncoding("utf-8");
OutputStream os=response.getOutputStream();
在使用第一種的時候,我用的ajax請求。導致excel無法導出,最後我直接請求可以導出(document.location.href="${pageContext.request.contextPath}/tran/export.do?")
原因是:ajax也用到了response.getWriter()方法 要將 數據結果回傳,這裏 我雖然 放棄了 回傳的寫入流writer 參數, 但是ajax還是會默認的去掉用,把流已經佔用了,當然返回不了任何東西了。
第二種:
action中使用
FileOutputStream fos=new FileOutputStream(file);
此時可以使用ajax請求,在導出成功後返回文件路徑,在頁面中使用window.open(path);即可打開導出的excel文件


以下爲生成Excel操作

看到一個比較好的文章詳細參見:http://blog.csdn.net/evangel_z/article/details/7332535

1.生成Excel文件並添加數據,Action中:

        添加響應事件,通過getExportPath獲得工程路徑,與jsp中獲得request.getContextPath()效果相同,fileName爲要下載的文件名,經過拼接filePath是xls文件的絕對路徑,調用工具類DownLoadUtil中的downLoadUtil方法;

	@RequestMapping("export.do")
	public void export(QueryRequest QueryRequest, HttpServletRequest request,HttpServletResponse response){
		try {
			EPageResponse<TranInfo> ePageInfo = this.tranService.tranExport(QueryRequest, this.getTranComm());
			String exportPath = this.getExportPath(request);
			WindDate wd = new WindDate();
			String fileName = wd.toYYYYMMDDHHMMSS()+ "繳費交易流水" +".xls";
			String filePath = exportPath + File.separator + fileName;
			WritableWorkbook book = Workbook.createWorkbook(new File(filePath));
			WritableSheet sheet = book.createSheet("交易流水列表", 0);
			
			this.setSheel(ePageInfo.getRows(),sheet);
			book.write();
			book.close();
			DownloadUtil.downFile(filePath, request, response);
			
		} catch (Exception e) {
			e.printStackTrace();
			String msg = e.getMessage();
			if (null == msg)
				msg = "其他異常 ";
		}
	}
    public String getExportPath(HttpServletRequest request){
        String path = (String) request.getSession().getServletContext().getInitParameter("EXPORT_PATH");
        File file = new File(path);
        if(!file.exists())file.mkdirs();
        return path;        
    }

2.彈出下載框,工具類DownLoadUtil中:

    public static void downFile(String filepath, HttpServletRequest request,HttpServletResponse response){
        try{
          File temFile = new File(filepath);
          if(!temFile.exists()){
              response.getWriter().write("ERROR:File Not Found");
              return ;
          }
          String fileName = filepath.substring(filepath.lastIndexOf(File.separator)+1);
          String browser = request.getHeader("user-agent");
          Pattern p = Pattern.compile(".*MSIE.*?;.*");
          Matcher m = p.matcher(browser);
           
          if(m.matches()){
              response.setHeader("Content-Disposition", "attachment; filename=" +URLEncoder.encode(fileName, "UTF-8").replace("+",""));
          }else{
              response.setHeader("Content-Disposition", "attachment; filename=" +new String(fileName.getBytes("UTF-8"),"ISO8859-1").replace(" ", ""));
          }
          response.setHeader("Cache-Control", "max-age=" + 100);
          response.setContentLength((int) temFile.length());
          response.setContentType("application/x-download");
          response.setHeader("windows-Target", "_blank");
          OutputStream ot=response.getOutputStream();
          BufferedInputStream bis  = new BufferedInputStream(new FileInputStream(temFile));
          BufferedOutputStream bos = new BufferedOutputStream(ot);
          byte[] buffer = new byte[4096];
          int length = 0;
          while((length = bis.read(buffer)) > 0){
              bos.write(buffer,0,length);
          }
          bos.close();
          bis.close();
          ot.close();
      } catch (Exception e) {
          e.printStackTrace();
      }
    }


發佈了77 篇原創文章 · 獲贊 9 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章