java excel 批量导入
public static List<String[]> getExcelData(MultipartFile file, int startRow) throws IOException {
int resultSize = 0;
ArrayList<String[]> resultData = new ArrayList<>(resultSize);
if (!checkFile(file)) {
return resultData;
}
Workbook workbook = getWorkBook(file);
if (workbook != null) {
Sheet sheet = workbook.getSheetAt(0);
if (sheet == null) {
return resultData;
}
resultSize = sheet.getLastRowNum() + 1;
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
for (int rowNum = firstRowNum + startRow; rowNum <= lastRowNum; rowNum++) {
Row row = sheet.getRow(rowNum);
if (rowIsEmpty(row)) {
break;
}
int firstCellNum = row.getFirstCellNum();
int lastCellNum = row.getLastCellNum();
String[] cells = new String[lastCellNum];
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
resultData.add(cells);
}
workbook.close();
}
return resultData;
}
使用上述方法将前台传来的 excel文件 转换为一个 List<String[]> ,然后循环List<String[]> 将 excel中的数据写入数据库。
|