public void updateExcel(@RequestBody MultipartFile file) { try{ Workbook workbook = getWorkBook(file);//獲取工作簿workbook Sheet sheetAt = workbook.getSheetAt(0);//根據工作簿獲取整張excel表的信息
for (int i=1; i<= sheetAt.getLastRowNum(); i++){//第一行是表頭,所以不要,i從1開始
for(int j=0; j < sheetAt.getRow(i).getLastCellNum(); j++){//循環每一行
Cell cell = sheetAt.getRow(i).getCell(j);//獲取每一個單元格的值 String value = getValue(cell);//把單元格的值轉成字符串 System.out.print(value+" "); } System.out.println(); } }catch(Exception e){ e.printStackTrace(); } } public static Workbook getWorkBook(MultipartFile file) { //獲得文件名 String fileName = file.getOriginalFilename(); //創建Workbook工作薄對象,表示整個excel Workbook workbook = null; Sheet sheet = null; try { //獲取excel文件的io流 InputStream is = file.getInputStream(); //根據文件后綴名不同(xls和xlsx)獲得不同的Workbook實現類對象 if(fileName.endsWith("xls")){ //2003 POIFSFileSystem poifsFileSystem = new POIFSFileSystem(is); workbook = new HSSFWorkbook(poifsFileSystem); sheet = workbook.getSheetAt(0); }else if(fileName.endsWith("xlsx")){ //2007 及2007以上 workbook = new XSSFWorkbook(is); sheet = workbook.getSheetAt(0); } } catch (IOException e) { e.printStackTrace(); } return workbook; } public static String getValue(Cell cell){ if(cell.getCellTypeEnum() == org.apache.poi.ss.usermodel.CellType.BOOLEAN){ return String.valueOf(cell.getBooleanCellValue()); }else if(cell.getCellTypeEnum() == org.apache.poi.ss.usermodel.CellType.NUMERIC){ String value = ""; if (HSSFDateUtil.isCellDateFormatted(cell)) { Date d = cell.getDateCellValue(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); value = sdf.format(d); }else{ double temp = cell.getNumericCellValue(); //value = new BigDecimal(temp).toString(); value = String.valueOf(temp); } return value; }else if (cell.getCellTypeEnum() == org.apache.poi.ss.usermodel.CellType.STRING){ return String.valueOf(cell.getStringCellValue()); }else{ return String.valueOf(cell.getStringCellValue()); } }