今天自己写了一遍解析Excel的方法,虽然也是根据网上一些例子来写的,但是一边写一边在网上查找这些类、方法的含义及左右,感觉还是有所收获的。
记录一下以后方便使用。
private static final String xls = "xls";
private static final String xlsx = "xlsx";
public static List<SQLEntity> excel(MultipartFile file) throws Exception {
Workbook workbook = getWorkBook(file);
List<SQLEntity> list = new ArrayList<>();
if(workbook == null) return list;
int sheetNum = workbook.getNumberOfSheets();
for(int num = 0; num < sheetNum; num++){
Sheet sheet = workbook.getSheetAt(num);
if(sheet == null) continue;
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
for(int rowNum = firstRowNum+1; rowNum <= lastRowNum; rowNum++){
Row row = sheet.getRow(rowNum);
if(row == null) continue;
int firstCellNum = row.getFirstCellNum();
int lastCellNum = row.getPhysicalNumberOfCells();
SQLEntity sqlEntity = new SQLEntity();
for(int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++){
Cell cell = row.getCell(cellNum);
String cellValue = getCellValue(cell);
switch (cellNum){
case 0:
sqlEntity.setName(cellValue);
break;
case 1:
sqlEntity.setDesc(cellValue);
break;
}
}
list.add(sqlEntity);
}
}
workbook.close();
return list;
}
public static Workbook getWorkBook(MultipartFile file) throws IOException {
Workbook workbook = null;
InputStream fis = file.getInputStream();;
BufferedInputStream bis = new BufferedInputStream(fis);
String[] splitName = file.getOriginalFilename().split("\\.");
String suffix = splitName[splitName.length-1];
if(splitName==null && !(xls.equals(suffix) || xlsx.equals(suffix))) return workbook;
switch(suffix){
case xls://2003及以下
workbook = new HSSFWorkbook(bis);
break;
case xlsx://2007及以上
workbook = new XSSFWorkbook(bis);
break;
}
return workbook;
}
public static String getCellValue(Cell cell){
String cellValue = "";
if(cell == null) return cellValue;
switch(cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC://数字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING://字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN://布尔
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA://公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_ERROR://错误
cellValue = "错误";
break;
case Cell.CELL_TYPE_BLANK://空
break;
default:
cellValue = "默认";
break;
}
return cellValue;
}