java:poi:上傳excel檔案並解析,處理資料(含postman測試呼叫)
阿新 • • 發佈:2022-03-23
java:poi:上傳excel檔案並解析,處理資料(含postman測試呼叫)
直接上程式碼:
-
// excel匯入
-
@CrossOrigin
-
@PostMapping(value = "/batch_sms_send/parseExcel", produces = {"application/json;charset=UTF-8"})
-
public void parseExcel(@RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse response
) {
-
try {
-
// @RequestParam("file") MultipartFile file 是用來接收前端傳遞過來的檔案
-
// 1.建立workbook物件,讀取整個文件
-
InputStream inputStream = file.getInputStream();
-
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
-
HSSFWorkbook wb = new HSSFWorkbook(poifsFileSystem);
-
// 2.讀取頁尾sheet
-
HSSFSheet sheetAt = wb.getSheetAt(0);
-
// 3.迴圈讀取某一行
-
for (Row row : sheetAt) {
-
//先將第二列手機號轉換為string格式
-
row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
-
// 4.讀取每一行的單元格
-
String stringCellValue="";
-
String stringCellValue2=""
;
-
if(row.getCell(0)!=null && row.getCell(1)!=null)
-
stringCellValue = row.getCell(0).getStringCellValue(); // 第一列資料
-
stringCellValue2 = row.getCell(1).getStringCellValue();// 第二列
-
// 寫多少個具體看大家上傳的檔案有多少列.....
-
// 測試是否讀取到資料,及資料的正確性
-
System.out.println(stringCellValue);
-
System.out.println(stringCellValue2);
-
}
-
} catch (Exception e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
-
}
pom:
-
<dependency>
-
<groupId>org.apache.poi</groupId>
-
<artifactId>poi-ooxml</artifactId>
-
<version>3.14</version>
-
</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