poi 导出excel 异常处理方式--曲线救国法

excel 导出不算什么新鲜的话题。目前各种生成excel的开源jar包,poi,jxtl等。但是下载过程中如果出现异常该如何处理呢。

翻了之前的几个项目中的excel导出,有的异常就直接抛了出去,有的打印了异常。Action 中异常已经在最顶层了,抛出显然不是明智之举。但是捕获异常之后不做任何处理,用户体验也不好。有人一定会问,那还不好办,定义一个异常标识,捕获异常之后传给页面,提示用户;没有异常就正常导出就好了吗!问题就在这里。我第一次的js的写法

window.location.href="policyExportInfo.action";

js定向到这个地址:然后执行一系列的excel组装操作,最后得到一个inputstream,然后我是用struts2的type=stream,直接将这个流输出。这是一个无返回值的操作,我根本得不到返回值。

那第二个方法,使用ajax。

$.ajax({
  url: "policyExportInfo.action",
  success: function(returnData){
	if(returnData==0){
		alert("导出失败,请重试");
	}
 });

这样子可已接受到返回值了吧!但问题是,如果导出成功,excel的inputstream也同样呗当做流返回回来了。查了一些资料使用ajax导出是不行的。

然后我想,如果是没有返回值的ajax,是不是行呢。

我在java 里面把异常信息print出来。

       response.reset();
            response.setContentType("text/html charset=GBK");
            try {
                response.getWriter().write("<script>");
                response.getWriter().write("alert('导出失败,请重试');");
                response.getWriter().write("</script>");
            } catch (IOException e1) {
                e1.printStackTrace();
            }

结果是否定的,不行。

折腾了2天之后,决定尝试最后一种方法,不行就放弃。

在java中定义一个标识,标志导出成功或者失败,如果导出成功就将这个excel存在服务器上(其实随便存在哪里都行了)。返回给页面的是这个标识。如果是导出成功的,执行下载操作,下载之后这个文件删除;

有人会问:那下载中的异常怎么办。在同一台服务器上,除非服务器挂了,否则下载失败是小概率事件,我觉得这个是可以忽略的。但是生成excel不同。这期间包含系统的逻辑处理,同时还会有一些跨服务器的访问,你这了没问题,难免别人不会有问题。

具体代码片段如下:

jsp中:

$.ajax({
		url: "policyExportInfo.action",
		
		success: function(returnData){
			if(returnData==0){
				alert("导出失败,请重试");
			}else{
				window.location.href="policyExportInfo.action";
			}
		}
	  });

java 中:

  1     public String policyExportInfo(){
  2         HttpServletResponse response = ServletActionContext.getResponse();
  3         HttpSession session = request.getSession();
  4         WrUser user = (WrUser) session.getAttribute("user");
  5         String userCode = user.getUserCode();
  6         String dirPath="";
  7         String excelPath = "";
  8         PubTools pTool = new PubTools();
  9         try {
 10             dirPath= pTool.getUrlBykey("sysconfig.filePath");
 11         } catch (IOException e2) {
 12             e2.printStackTrace();
 13         }
 14         excelPath = dirPath + "//" + userCode + new DateTime(new Date(), new DateTime().YEAR_TO_DAY);//导出excel存放的路径
 15         logger.info(excelPath);
 16         File uploadFilePath = new File(excelPath);
 17         // 如果该目录不存在,则创建之
 18         if (uploadFilePath.exists() == false) {
 19             uploadFilePath.mkdirs();
 20         }
 21         String as = excelPath + "//" + "承保查询"+new DateTime(new Date(), new DateTime().YEAR_TO_DAY)+".xls";
 22         session.setAttribute("exportFile", as);//下载文件
 23         File myFilePath = new File(as);
 24         if (!myFilePath.exists()) {
 25             GcspPolicy policy = (GcspPolicy) session.getAttribute("policy");//获取查询对象
 26             if(user!=null&&policy!=null){
 27                 policy.setThisComCode(user.getComCode());
 28             }
 29             custType = user.getCustType();
 30             
 31             String reqXML = this.getXML(custType,"POLICYEXPORT",policy);
 32             GcspServerClient client = new GcspServerClient();
 33           //  String xmlData1="E:\\policyReturn.txt";
 34            // String returnValue = this.readFile(xmlData1);
 35             String returnValue = "";
 36             String returnValueDecompress = "";
 37             response.setContentType("text/html; charset=UTF-8");
 38             ServletOutputStream out = null;
 39             try {
 40                 out = response.getOutputStream();
 41             } catch (IOException e1) {
 42                 e1.printStackTrace();
 43             }
 44             try {
 45                 
 46                 //总线保存采用GZIP压缩,并用base64转码;接收到总线返回报文后,需先使用base64解码,并解压缩
 47                 returnValue = client.requestXML(reqXML);//获取报文
 48                 byte[] b = new sun.misc.BASE64Decoder().decodeBuffer(returnValue);//使用BASE64解码
 49                 byte[] b1= client.decompress(b);//解压缩
 50                 StringUtil s= new StringUtil();
 51                 returnValueDecompress = s.byteToChar(b1, "GBK");
 52                 policyList = new ArrayList<GcspPolicy> ();
 53                 
 54                 String rtnPage = this.messageParsingPage(returnValueDecompress);
 55                 if(rtnPage.contains(";")){
 56                     String strTemp[] = rtnPage.split(";");
 57                     if(strTemp.length>0){
 58                          policyList = this.messageParsingPolicy(returnValueDecompress);
 59                     }
 60                 } else {
 61                     out.print("0");
 62                     return "none";
 63                 }
 64                
 65                 if(policyList!= null){
 66                     HSSFWorkbook workbook;
 67                      workbook = exportExcelStyle(policyList);
 68                      
 69                      FileOutputStream output = new FileOutputStream(as); // 输出流
 70                      //ByteArrayOutputStream output = new ByteArrayOutputStream();
 71                      workbook.write(output);
 72                      output.flush();
 73                      //byte[] ba = output.toByteArray();
 74                      //inputStream = new ByteArrayInputStream(ba,0,ba.length);
 75                      
 76                      output.close();
 77                 }else{
 78                     out.print("0");
 79                     return "none";
 80                 }
 81             } catch (Exception e) {
 82                 try {
 83                     out.print("0");
 84                     return "none";
 85                 } catch (IOException e1) {
 86                     e1.printStackTrace();
 87                 }
 88             }
 89             try {
 90                 out.print("1");
 91                 return "none";
 92             } catch (IOException e) {
 93                 e.printStackTrace();
 94             }
 95         }else{
 96             //下载
 97             String exportFile = (String) session.getAttribute("exportFile");
 98             try {
 99                 Downfile  downfile = new Downfile();
100                 downfile.downfileByPath(response, request, exportFile);
101                 downfile.deleteDirectory(excelPath);// 删除excel 文件夹
102                 downfile.deleteFile(exportFile);// 删除生成的压缩文件
103             } catch (IOException e) {
104                 e.printStackTrace();
105             }
106         }
107         
108         return "none";
109     }

  

 

以上是个人的一点小小愚见,欢迎拍砖!

 

 

 

 

posted on 2014-06-23 13:13  依米艳  阅读(1638)  评论(0编辑  收藏  举报

导航