EXCEL文件解析备忘录(03.07通用哦)

这种读取数据的方式是将表格中所有不为空的sheet,row行都逐条读取,读取为List<list<String>>的格式又防止了数据的异常显示,再根据具体的业务需求对逐条的记录进行处理
public static List<List<String>> readExcel(MultipartFile file) throws IOException {
    if (file == null){
        throw new RuntimeException("文件流为空");
    }
    String format = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
    Workbook workbook = null;
    if (format.equals("xls")){
        workbook = new HSSFWorkbook(file.getInputStream());
    } else if (format.equals("xlsx")) {
        workbook = new XSSFWorkbook(file.getInputStream());
    } else {
        throw new RuntimeException("文件类型错误!");
    }
    List<List<String>> result = new ArrayList<List<String>>();
    int size = workbook.getNumberOfSheets();
    // 循环每一页,并处理当前循环页
    for (int numSheet = 0; numSheet < size; numSheet++) {
        // Sheet 标识某一页
        Sheet sheet = workbook.getSheetAt(numSheet);
        if (sheet == null) {
            continue;
        }
        // 处理当前页,循环读取每一行
        for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
            // Row表示行
            Row row = sheet.getRow(rowNum);
            if (row == null){
                continue;
            }
            int minColIx = row.getFirstCellNum();
            int maxColIx = row.getLastCellNum();
            List<String> rowList = new ArrayList<String>();
            // 遍历改行,获取处理每个cell元素
            for (int colIx = minColIx; colIx < maxColIx; colIx++) {
                // Cell 表示单元格
                Cell cell = row.getCell(colIx);
                if (cell == null) {
                    continue;
                }
                rowList.add(getStringVal(cell));
            }
            result.add(rowList);
        }
    }
    return result;
}

public static String getStringVal(Cell cell) {
    switch (cell.getCellType()) {
        case BOOLEAN:
            return cell.getBooleanCellValue() ? "TRUE" : "FALSE";
        case FORMULA:
            return cell.getCellFormula();
        case NUMERIC:
            cell.setCellType(STRING);
            return cell.getStringCellValue();
        case STRING:
            return cell.getStringCellValue();
        default:
            return "";
    }
}

猜你喜欢

转载自blog.csdn.net/a1_HelloWord/article/details/84720327