直接上代碼:
// 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
excel文件內容:
代碼中取出值並打印:
參考: