poi實現Excel文件的讀取

1.前端代碼

$("#upload").on('click', function() {
  var formData = new FormData();
  var name = $("#uploadFile").val();
  formData.append("fileupload", $("#articleImageFile")[0].files[0]);
  formData.append("name", name); //這個地方能夠傳遞多個參數
  if(name == null || name == ''){
    alert("請選擇上傳文件");
  }
  $.ajax({
    type: 'post',
    url: commenUrl + "/fileUpload",
    async: false,
    data: formData,
    // 告訴jQuery不要去處理髮送的數據
    processData: false,
    // 告訴jQuery不要去設置Content-Type請求頭
    contentType: false,
    beforeSend: function() {
    console.log("正在進行,請稍候");
    },
    success: function(data) {
      if(data.code == 0) {
        alert("導入成功");
        $("#myModal").modal('hide');//隱藏模態框
      }else {
        alert("導入失敗");
      };
    }
  });
});

2.控制層代碼

    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public void  fileUpload(@RequestParam("fileupload")MultipartFile fileupload, HttpServletRequest request,
            HttpServletResponse response, ApiJsonResult result) {
        try {
            result = uploadService.fileUpload(fileupload,result);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(StatusCodeEnum.EXTREMELY.getCode());
            result.setMsg(StatusCodeEnum.EXTREMELY.getDesc());
        }
        JsonWebPrintUtils.printApiResult(request, response, result);
    }    

3.實現代碼

  excel中存在純數字的數據時,可使用getNumericCellValue()取值,或者使用setCellType(Cell.CELL_TYPE_STRING)統一設置爲字符串格式讀取。實際應用中可根據實際狀況在讀取過程當中對讀取到的數據進行校驗返回錯誤信息到客戶端。前端

  @Override
    public ApiJsonResult fileUpload(MultipartFile fileupload, ApiJsonResult result) throws IOException{
     //獲取文件名 String fileName
= fileupload.getOriginalFilename(); Workbook workbook = getWorkbook(fileName,fileupload);

      if(fileName.endsWith(XLS)) {
        //2003
        workbook = new HSSFWorkbook(fileupload.getInputStream());
      }else if(fileName.endsWith(XLSX)) {
        //2007
        workbook = new XSSFWorkbook(fileupload.getInputStream());
      }ajax

     //建立工做表sheet
        Sheet sheet = this.getSheet(workbook, 0);

      //獲取sheet中數據的行
      int rows = sheet.getPhysicalNumberOfRows();數據庫

      List<UploadTest> lsit = new ArrayList<>();//用於存放讀取到的數據app

      for(int i=1;i<row.length;i++){//從第二行開始讀取數據async

        Row row = sheet.getRow(i);ide

        row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);//設置讀取數據類型爲string
        row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);//設置讀取數據類型爲string
        String value1 = row.getCell(0).getStringCellValue();//第一列的值
        String value2 = row.getCell(1).getStringCellValue();//第二列的值post

        UploadTest test = new UploadTest(); //建立實體類接受值this

        test.setPig(value1);url

        test.setDog(value2);spa

        list.add(test);

      }

      //將數據寫入數據庫

      ...............省略

     return this.getCarAndDeviceBindData(sheet,result);
    }
相關文章
相關標籤/搜索