Java上傳下載excel、解析Excel、生成Excel的問題

在軟件開發過程中難免需要批量上傳與下載,生成報表保存也是常有之事。

1.Excel的下載

      1)Action中:

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



 public ActionForward downLoadExcelModel(ActionMapping actionMapping,
           ActionForm actionForm, HttpServletRequest request,
           HttpServletResponse response) throws Exception {
           String path = request.getSession().getServletContext().getRealPath(
            "/resources");
           String fileName = "成員模版.xls";
           String filePath = path + "\\" + fileName;
           DownLoadUtil.downLoadFile(filePath, response, fileName, "xls");
           return null;
        }

    2)工具類DownLoadUtil中:

<span style="background-color: rgb(191, 205, 172);"> </span><span style="background-color: rgb(255, 255, 255);">public static boolean downLoadFile(String filePath,
        HttpServletResponse response, String fileName, String fileType)
        throws Exception {
        File file = new File(filePath);  //根據文件路徑獲得File文件
        //設置文件類型(這樣設置就不止是下Excel文件了,一舉多得)
        if("pdf".equals(fileType)){
           response.setContentType("application/pdf;charset=GBK");
        }else if("xls".equals(fileType)){
           response.setContentType("application/msexcel;charset=GBK");
        }else if("doc".equals(fileType)){
           response.setContentType("application/msword;charset=GBK");
        }
        //文件名
        response.setHeader("Content-Disposition", "attachment;filename=\""
            + new String(fileName.getBytes(), "ISO8859-1") + "\"");
        response.setContentLength((int) file.length());
        byte[] buffer = new byte[4096];// 緩衝區
        BufferedOutputStream output = null;
        BufferedInputStream input = null;
        try {
          output = new BufferedOutputStream(response.getOutputStream());
          input = new BufferedInputStream(new FileInputStream(file));
          int n = -1;
          //遍歷,開始下載
          while ((n = input.read(buffer, 0, 4096)) > -1) {
             output.write(buffer, 0, n);
          }
          output.flush();   //不可少
          response.flushBuffer();//不可少
        } catch (Exception e) {
          //異常自己捕捉       
        } finally {
           //關閉流,不可少
           if (input != null)
                input.close();
           if (output != null)
                output.close();
        }
       return false;
    }
    這樣,就可以完成文件的下載,java程序將文件以流的形式,保存到客戶本機!!</span>

2、Excel的上傳與解析(此處方面起見,ExcelN行兩列,以爲手機號,另一爲短號)

    對於數據批量上傳,就涉及到文件的上傳與數據的解析功能,此處運用了第三方jar包,方便快捷。對於文件上傳,用到了commons-fileupload-1.1.1.jar與commons-io-1.1.jar,代碼中並沒有導入common-io包中的內容,而fielupload包的上傳依賴於common-io,所以兩者皆不可少;而對於Excel的解析,此處用到了jxl-2.6.jar。下面通過代碼對各步驟進行解析。

<span style="background-color: rgb(255, 255, 255);"> 1)jsp文件:
      對於文件的上傳,強烈推薦使用form表單,並設置enctype="multipart/form-data" method="post",action爲處理文件的路徑
      <form id="fileUpload" action="excel.do?method=exportMemberExcel" enctype="multipart/form-data" method="post">
      <input id="excelFile" name="file" type="file"/>
      <input type="button" value="提交" onclick="submitExcel()"/>
  </form>
    2)js文件:
      通過js文件對上傳的文件進行初識的格式驗證,判斷是否爲空以及格式是否正確,正確的話提交表單,由後臺對上傳的文件處理,此處用的是jQuery,需要導入jquery-***.js,此處使用的是jquery-1.4.2.min.js(最後提供下載地址)。
    function submitExcel(){
       var excelFile = $("#excelFile").val();
       if(excelFile=='') {alert("請選擇需上傳的文件!");return false;}
       if(excelFile.indexOf('.xls')==-1){alert("文件格式不正確,請選擇正確的Excel文件(後綴名.xls)!");return false;}
       $("#fileUpload").submit();
    }
    3)Action中:
     使用common-fileupload包中的類FileItemFactory,ServletFileUpload對請求進行處理,如果是文件,用工具累ExcelUtil處理,不是文件,此處未處理,不過以後開發可以根據需要處理,此處不纍述。(因爲如果Excel中如果存在錯誤記錄,還需供用戶下載,所以若有錯誤信息,暫保存在session中,待用戶下載後可清空此session)。
      public ActionForward exportMemberExcel(ActionMapping actionMapping,
          ActionForm actionForm, HttpServletRequest request,
          HttpServletResponse response) throws Exception {
      int maxPostSize = 1000 * 1024 * 1024;
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
      servletFileUpload.setSizeMax(maxPostSize);
      try {
      List fileItems = servletFileUpload.parseRequest(request);
      Iterator iter = fileItems.iterator();
      while (iter.hasNext()) {
          FileItem item = (FileItem) iter.next();
          if (!item.isFormField()) {// 是文件
          Map map = ExcelUtil.excel2PhoneList(item.getInputStream());
     String[][] error = (String[][]) map.get("error");
     
     if (error.length != 0) {
      //如果存在錯誤,存入內存,供用戶保存
      request.setAttribute("errorFlag", "ture");
      request.getSession().setAttribute("exportMap", map);
     } else {
      request.setAttribute("errorFalg", "false");
      // 獲取正確的值填寫json
      String phoneJson = JsonUtil
        .phoneArray2Json((String[][]) map
          .get("current"));
      request.setAttribute("phoneJson", phoneJson);
     }
    } else {    //不是文件,此處不處理,對於text,password等文本框可在此處理
        logger.error("wrong file");
    }
   }
  } catch (Exception e) {
   logger.error("invoke fileUpload error.", e);
  }
  return actionMapping.findForward("queryAccounts");
 }</span>

<span style="background-color: rgb(255, 255, 255);">4、工具類ExcelUtil
   主要藉助jxl包對Excel文件進行解析,獲取正確信息以及錯誤信息,供用戶取捨。
   public static Map excel2PhoneList(InputStream inputStream) throws Exception {
     Map map = new HashMap();
     Workbook workbook = Workbook.getWorkbook(inputStream);  //處理輸入流
     Sheet sheet = workbook.getSheet(0);// 獲取第一個sheet
     int rows = sheet.getRows();   //獲取總行號
     String[][] curArr = new String[rows][2];     //存放正確心細
     String[][] errorArr = new String[rows * 2][4];   //存放錯誤信息
     int curLines = 0;
     int errorLines = 0;
  for (int i = 1; i < rows; i++) {// 遍歷行獲得每行信息
     String phone = sheet.getCell(0, i).getContents();// 獲得第i行第1列信息
     String shortNum = sheet.getCell(1, i).getContents();// 短號
     StringBuffer errorMsg = new StringBuffer();
     if (!isRowEmpty(sheet, i)) { //此行不爲空
        //對此行信息進行正誤判斷           
     }
  }// 行
  //正誤信息存入map,保存
  map.put("current", current);
  map.put("error", error);
   return map;
 }
   private static boolean isRowEmpty(Sheet sheet, int i) {
    String phone = sheet.getCell(0, i).getContents();// 集團編號
    String shortNum = sheet.getCell(1, i).getContents();// 集團名稱
    if (isEmpty(phone) && isEmpty(shortNum))
        return true;
    return false;
   }
  返回值由Action處理,此處爲止,Excel的解析就完成了!</span>

<span style="background-color: rgb(255, 255, 255);">3 生成Excel
  上文中說到如果存在錯誤信息,可供用戶下載,錯誤信息存在Session中,下載就需要利用Session中的數據生成Excel文檔,供用戶保存。
   1)Action中:
   Action從Session中獲取保存的對象,調用工具類保存,然後刪除Session中的內容.
   public ActionForward downErrorExcel(ActionMapping actionMapping,
      ActionForm actionForm, HttpServletRequest request,
      HttpServletResponse response) throws Exception {
     Map map = (Map) request.getSession().getAttribute("exportMap");
     ExcelUtil.createExcel(response, map);
     request.getSession.removeAttribure("exportMap");
     return null;
    }
  2)工具類ExcelUtil中:
     public static boolean createExcel(HttpServletResponse response, Map map) {
     WritableWorkbook wbook = null;
     WritableSheet sheet = null;
     OutputStream os = null;
     try {
       response.reset();   
       //生成文件名
       response.setHeader("Content-disposition", "attachment; filename="
           + new String("錯誤信息".getBytes("GB2312"), "ISO8859-1")
           + ".xls");
       response.setContentType("application/msexcel");
       os = response.getOutputStream();
       wbook = Workbook.createWorkbook(os);
       sheet = wbook.createSheet("信息", 0);
       int row = 0;
       //填寫表頭
       setSheetTitle(sheet, row);
       //遍歷map,填充數據
       setSheetData(sheet, map, row);
       wbook.write();
       os.flush();
     } catch (Exception e) {
       //自己處理
     }finally {
         try {//切記,此處一定要關閉流,否則你會下載一個空文件
          if (wbook != null)
              wbook.close();
          if (os != null)
              os.close();
         } catch (IOException e) {
            e.printStackTrace();
         } catch (WriteException e) {
            e.printStackTrace();
      }
  }
  return false;
 }
 
private static void setSheetTitle(WritableSheet sheet, int row)
   throws RowsExceededException, WriteException {
  // 設置excel標題格式
  WritableFont wfont = new WritableFont(WritableFont.ARIAL, 12,
    WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
    Colour.BLACK);
  WritableCellFormat wcfFC = new WritableCellFormat(wfont);
  //設置每一列寬度
  sheet.setColumnView(0,13);
  sheet.setColumnView(1,13);
  sheet.setColumnView(2,13);
  sheet.setColumnView(3,50);
  //填寫第一行提示信息
  sheet.addCell(new Label(0, row, "手機號碼", wcfFC));
  sheet.addCell(new Label(1, row, "短號", wcfFC));
  sheet.addCell(new Label(2, row, "原錯誤行號", wcfFC));
  sheet.addCell(new Label(3, row, "錯誤原因", wcfFC));
 }
 private static void setSheetData(WritableSheet sheet, Map map, int row)
   throws RowsExceededException, WriteException {
  WritableFont wfont = new WritableFont(WritableFont.ARIAL, 10,
    WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
    Colour.RED);
  WritableCellFormat wcfFC = new WritableCellFormat(wfont);
  //從map中獲取數據
  String[][] error = (String[][]) map.get("error");
  //遍歷並填充
  for (int i = 0; i < error.length; i++) {
   row++;
   sheet.addCell(new Label(0, row, error[i][0]));
   sheet.addCell(new Label(1, row, error[i][1]));
   sheet.addCell(new Label(2, row, error[i][2]));
   sheet.addCell(new Label(3, row, error[i][3],wcfFC));
  }
 }</span>

 Excel文件生成之後,由response傳給客戶,客戶選擇路徑,就可以下載了,至此,完成了Excel文件下載、解析、和生成的工作,大功一件,希望有所啓發。

    另外,補充一下,火狐fireFox在上傳文件時,服務器端並不能獲取客戶端存取文件的絕對路徑,而只是一個文件名,ie8以及低版本上傳文件時,服務器可以獲得絕對路徑,這是火狐的安全機制決定的,所以試圖根據上傳的文件路徑,對文件修改然後保存到原文件,這種是不可取的,一者是因爲火狐下獲取不到文件路徑,二者即使服務器在ie下獲得了文件的絕對路徑,在創建並修改文件時也只是生成在服務器端,並不能修改客戶端的文件,只是提醒下,網上有解決方法,可以自行查閱。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章