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

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

1.完成目標

讀取.csv .xls .xlsx檔案型別的檔案,根據表頭在表中建立表,根據資料插入表中

2.實現

2.1 ivy.xml相關依賴包:
    <dependency org="ossjava" name="opencsv" rev="2.3" conf="compile;web-inf-lib" />
    <dependency org="ossjava" name="poi" rev="3.8+" conf="compile;web-inf-lib" />
2.2 前臺頁面upload.jsp:
<form class="fileForm" enctype="multipart/form-data" method="post">

<input type="file" id="excelFile" name="excelFile" style="width:400px;"

    accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" >
   <input type="button" value="Submit" onclick="doUpload()" class="submit" style="width:100px"/>    <div style="float:left;text-align:left;width:80%;font-weight:bold;" id="uploadHint"></div>
 </form>


<script type="text/javascript">

function doUpload() {

  var formData = new FormData($(".fileForm" )[0]); 
     $.ajax({ 
         url: 'doUpload.action' , 
         type: 'POST', 
         data: formData, 
         dataType: 'json', 
         contentType: false, 
         processData: false,

          error : function() {
               $("#uploadHint").html("<span style='color:red;'>upload failed, please try again</span>");
          },
          success : function(json) {
           if(json != null && json.status != undefined && json.status == "200") {
                $("#uploadHint").html("<span style='color:red;'>"+json.message+"</span>");
           }
           else {
                $("#uploadHint").html("<span style='color:red;'>successfully!</span>");
           }
           }
        });
}  
</script>

2.3 applicationContext.xml
<bean name="uploadAction" class="action.UploadAction" scope="prototype">
     <property name="uploadService" ref="uploadService" />
    </bean>
    <bean name="uploadService" class="service.UploadServiceImpl" scope="singleton">
     <property name="uploadDao" ref="uploadDao" />
    </bean>
    <bean name="uploadDao" class="dao.UploadDao" scope="singleton">
     <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>

2.4 struts.xml
上傳檔案大小限制: <constant name="struts.multipart.maxSize" value="20971520"/> 

<action name="doUpload" class="uploadAction" method="doUpload">
</action>

2.5 Action
public class UploadAction extends ActionSupport { private static final long serialVersionUID = 1L;
 
 private static final Logger logger = LoggerFactory.getLogger(UploadAction.class);
 
 private UploadService uploadService;
 private File excelFile;
 private String excelFileFileName;
 private Map<String, Object> result = new HashMap<String, Object>();
 public static boolean isCsv(String filePath) { 
        return filePath.matches("^.+\\.(?i)(csv)$"); 
    }
 
    public Workbook createWorkBook(InputStream is) throws IOException{   
        if(excelFileFileName.toLowerCase().endsWith("xls")){   
            return new HSSFWorkbook(is);   
        }else if(excelFileFileName.toLowerCase().endsWith("xlsx")){ 
            return new XSSFWorkbook(is); 
        }else{ 
            return null; 
        } 
    } 
public String doUpload() throws Exception
 {
  logger.debug("-----------Start upload----------");
  try {
  if (isCsv(excelFileFileName)) { 
            String reString = importCsvFile();
            if(reString!=null && ERROR.equals(reString)){
       HttpServletResponse response = ServletActionContext.getResponse();
       JSONObject json = JSONObject.fromObject(result);
       PrintWriter out = response.getWriter();
       out.print(json);
            }
            logger.debug("-----------End upload----------");
            return null;
        }
   //處理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;
 }  public static String getCellValue(Cell cell) {
        if (cell != null) {
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_BLANK:
                return "";
            case Cell.CELL_TYPE_NUMERIC:
                String strValue = String.valueOf(cell.getNumericCellValue());
                if (strValue != null && strValue.indexOf(".") != -1
                        && strValue.indexOf("E") != -1) {
                    try {
                        return new DecimalFormat().parse(strValue).toString();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    if (strValue.endsWith(".0")) {
                        return strValue.substring(0, strValue.indexOf(".0"));
                    } else {
                        return strValue;
                    }
                }
            case Cell.CELL_TYPE_STRING:
                return (cell.getStringCellValue() + "").trim();
            case Cell.CELL_TYPE_FORMULA:
                return (cell.getCellFormula() + "").trim();
            case Cell.CELL_TYPE_BOOLEAN:
                return cell.getBooleanCellValue() + "";
            case Cell.CELL_TYPE_ERROR:
                return cell.getErrorCellValue() + "";
            }
        }
        return "";
    }

public File getExcelFile() {
  return excelFile;
 }
 public void setExcelFile(File excelFile) {
  this.excelFile = excelFile;
 }
 public String getExcelFileFileName() {    
        return excelFileFileName;    
    }
    public void setExcelFileFileName(String excelFileFileName) {    
        this.excelFileFileName = excelFileFileName;    
    }
 public UploadService getUploadService() {
  return uploadService;
 }
 public void setUploadService(UploadService uploadService) {
  this.uploadService = uploadService;
 } public Map<String, Object> getResult() {
  return result;
 }  public void setResult(Map<String, Object> result) {
  this.result = result;
 }