1. 程式人生 > 其它 >java:poi:上傳excel檔案並解析,處理資料(含postman測試呼叫)

java:poi:上傳excel檔案並解析,處理資料(含postman測試呼叫)

java:poi:上傳excel檔案並解析,處理資料(含postman測試呼叫)

直接上程式碼:

  1. // excel匯入
  2. @CrossOrigin
  3. @PostMapping(value = "/batch_sms_send/parseExcel", produces = {"application/json;charset=UTF-8"})
  4. public void parseExcel(@RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse response
    ) {
  5. try {
  6. // @RequestParam("file") MultipartFile file 是用來接收前端傳遞過來的檔案
  7. // 1.建立workbook物件,讀取整個文件
  8. InputStream inputStream = file.getInputStream();
  9. POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
  10. HSSFWorkbook wb = new HSSFWorkbook(poifsFileSystem);
  11. // 2.讀取頁尾sheet
  12. HSSFSheet sheetAt = wb.getSheetAt(0);
  13. // 3.迴圈讀取某一行
  14. for (Row row : sheetAt) {
  15. //先將第二列手機號轉換為string格式
  16. row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
  17. // 4.讀取每一行的單元格
  18. String stringCellValue="";
  19. String stringCellValue2=""
    ;
  20. if(row.getCell(0)!=null && row.getCell(1)!=null)
  21. stringCellValue = row.getCell(0).getStringCellValue(); // 第一列資料
  22. stringCellValue2 = row.getCell(1).getStringCellValue();// 第二列
  23. // 寫多少個具體看大家上傳的檔案有多少列.....
  24. // 測試是否讀取到資料,及資料的正確性
  25. System.out.println(stringCellValue);
  26. System.out.println(stringCellValue2);
  27. }
  28. } catch (Exception e) {
  29. // TODO Auto-generated catch block
  30. e.printStackTrace();
  31. }
  32. }

pom:

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi-ooxml</artifactId>
  4. <version>3.14</version>
  5. </dependency>

 

postman呼叫方法:

Content-Type    multipart/form-data  (這裡不設定應該postman會自動識別,應該也可以)

 

excel檔案內容:

程式碼中取出值並列印:

參考:

https://blog.csdn.net/zxs281/article/details/80856251 

</article>

https://blog.csdn.net/weixin_38750084/article/details/105796044