1. 程式人生 > >Struts2+Spring讀取csv和excel檔案,FormData Ajax提交

Struts2+Spring讀取csv和excel檔案,FormData Ajax提交

//處理excel檔案
  Workbook book = createWorkBook(new FileInputStream(excelFile)); 
     Sheet sheet = book.getSheetAt(book.getActiveSheetIndex()); 
     int lastRowNum = sheet.getLastRowNum();
     logger.debug("-----row number: " + lastRowNum);
   
     //1. if table doesn't exist, create table according to the excel
     int headCellNum = 0 ;
     Row headrow = sheet.getRow(0);
     headCellNum = headrow.getPhysicalNumberOfCells();
    
     boolean isExisted = uploadService.existTable(tableName);
        if(!isExisted){
         List<String> colList = new ArrayList<String>();
            for (int colCount = 0; colCount < headCellNum; colCount++) {
              Cell cell = headrow.getCell((short) colCount);
              String content = getCellValue(cell).trim();
           String regEx =  "[^a-zA-Z0-9#$]";    
              Pattern p = Pattern.compile(regEx);     
              Matcher m = p.matcher(content);     
              content = m.replaceAll("").trim();
              if(content.length()>30){
               content = content.substring(0,30);
              }
              content = content.replaceAll(" ", "").trim();
              colList.add(content);
            }
           
         logger.debug("create table " + tableName);
   uploadService.createTable(tableName, colList);
         /*logger.error("temp table doesn't exist!");
      return ERROR;*/
        }
       
        List<String> columns = uploadService.queryTableColumns(tableName);
        if(isExisted && headCellNum!=columns.size()){
      logger.error("file column number != table column number");
      
   result.put("status", "200");
   result.put("message", "file column number != table column number.");
   
   HttpServletResponse response = ServletActionContext.getResponse();
   JSONObject json = JSONObject.fromObject(result);
   PrintWriter out = response.getWriter();
   out.print(json);
   
   logger.debug("-----------End upload----------");
      return null;
     }
        if(isExisted && lastRowNum>0){
      logger.debug("clear table");
      uploadService.delete(tableName);
     }
    
        //2.insert records
     for (int i = 1;i <=lastRowNum;i++){ 
         Row row = sheet.getRow(i);
         if(row == null){ 
                continue; 
            } 
         int lastCellNum = row.getPhysicalNumberOfCells();
         List<String> cellList = new ArrayList<String>();
         for (int colCount = 0; colCount < lastCellNum; colCount++) {
           Cell cell = row.getCell((short) colCount);
           String content = getCellValue(cell).trim();
           cellList.add(content);
         }
       
   logger.debug("insert table " + tableName+" : "+i);
   uploadService.insert(tableName, columns, cellList);
        }
  } catch (IOException e) {
   result.put("status", "200");
   result.put("message", "upload failed, please try again!");
   
   HttpServletResponse response = ServletActionContext.getResponse();
   JSONObject json = JSONObject.fromObject(result);
   PrintWriter out = response.getWriter();
   out.print(json);
  }
  
     logger.debug("-----------End upload----------");
     return null;
 }
 
 private String importCsvFile() throws IOException {
  InputStreamReader inputStream = null; 
        CSVReader reader = null; 
        int rowSize = 0; 
        boolean isExisted = uploadService.existTable(tableName);
        List<String> columns = uploadService.queryTableColumns(tableName);
        try { 
            inputStream = new InputStreamReader(new FileInputStream(excelFile)); 
            reader = new CSVReader(inputStream); 
            String[] nextRow = null; 
            int i = 0; 
            while ((nextRow = reader.readNext()) != null) { 
             if(i==0){
              rowSize = nextRow.length; 
                }
             if(i==0 && isExisted && rowSize!=columns.size()){
              logger.error("file column number != table column number");
              result.put("status", "200");
           result.put("message", "file column number != table column number.");
              return ERROR;
             }
             if(i==0 && !isExisted){
              List<String> colList = new ArrayList<String>();
                    for (int colCount = 0; colCount < rowSize; colCount++) {
                      String content = nextRow[colCount].trim();
                   String regEx =  "[^a-zA-Z0-9#$]";    
                      Pattern p = Pattern.compile(regEx);     
                      Matcher m = p.matcher(content);     
                      content = m.replaceAll("").trim();
                      if(content.length()>30){
                       content = content.substring(0,30);
                      }
                      content = content.replaceAll(" ", "").trim();
                      colList.add(content);
                    }
                   
                 logger.debug("create table " + tableName);
           uploadService.createTable(tableName, colList);
           columns = uploadService.queryTableColumns(tableName);
                 /*logger.error("temp table doesn't exist!");
              return ERROR;*/
                }
                if (nextRow == null || nextRow.length <= 0) { 
                    continue; 
                }
                if(i==0 && isExisted && rowSize>0){
              logger.debug("clear table");
              uploadService.delete(tableName);
             }
               
                if(i!=0){
                 List<String> cellList = new ArrayList<String>();
                 for (int j = 0;j <rowSize;j++){ 
                  cellList.add(nextRow[j].trim());
                 }
                 logger.debug("insert table " + tableName+" : "+i);
           uploadService.insert(tableName, columns, cellList);
                }
                ++i; 
            } 
            reader.close(); 
            inputStream.close(); 
        } catch (IOException e) { 
   throw e;
        } finally { 
            if (inputStream != null) { 
                try { 
                    inputStream.close(); 
                } catch (IOException e) { 
                    inputStream = null; 
                    e.printStackTrace(); 
                } 
            } 
            if (reader != null) { 
                try { 
                    reader.close(); 
                } catch (IOException e) { 
                    reader = null; 
                    e.printStackTrace(); 
                } 
            } 
        } 
        return SUCCESS;
 }