Excel解析之POI解析
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List;
private List<BottomUserImport> getBottomUsersFromExcel(InputStream inputStream) throws IOException { List<BottomUserImport> arrayList = new ArrayList<>(); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); XSSFSheet sheet = workbook.getSheetAt(0); FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); for (Row row : sheet) { if(row.getRowNum() == 0){ Assert.isTrue(row.getPhysicalNumberOfCells() == 5 && "网点名称".equals(getCellValue(row.getCell(0), evaluator)) && "网点代码".equals(getCellValue(row.getCell(1), evaluator)) && "小哥姓名".equals(getCellValue(row.getCell(2), evaluator)) && "小哥工号".equals(getCellValue(row.getCell(3), evaluator)) && "兜底状态(今日是否兜底)".equals(getCellValue(row.getCell(4), evaluator)), "导入文件与模板不符,请下载最新模板!"); }else { BottomUserImport user = new BottomUserImport(); user.setDeptName(getCellValue(row.getCell(0), evaluator)); user.setDeptCode(getCellValue(row.getCell(1), evaluator)); user.setUserName(getCellValue(row.getCell(2), evaluator)); user.setUserId(getCellValue(row.getCell(3), evaluator)); user.setStatus(getCellValue(row.getCell(4), evaluator)); if (StringUtils.hasText(user.getDeptCode()) || StringUtils.hasText(user.getDeptName()) || StringUtils.hasText(user.getUserId()) || StringUtils.hasText(user.getUserName()) || StringUtils.hasText(user.getStatus())) { arrayList.add(user); //sheet.getPhysicalNumberOfRows()无法排除只有空字符串的行 Assert.isTrue(arrayList.size() <= 5000, "导入记录数不能超过5000"); } } } return arrayList; } private String getCellValue(Cell cell, FormulaEvaluator evaluator) { if (cell == null) { return ""; } CellValue cellValue = evaluator.evaluate(cell); if(cellValue == null){ return ""; } switch (cellValue.getCellType()){ case NUMERIC: double numberValue = cellValue.getNumberValue(); return String.valueOf((int) numberValue); default: return cellValue.getStringValue(); } } |