如何使用XSSFWorkbook读取文本薄?

【版权声明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权)
https://www.cnblogs.com/cnb-yuchen/p/18146625
出自【进步*于辰的博客

1、文件兼容类型。

// 兼容文件后缀列表
private static final String FILE_TYPE;
static {
    FILE_TYPE = ".xls/.xlsx/.csv";
}

2、文件检查。

/**
 * 文件有效性检查
 *
 * @param dataFile 数据文件
 * @return  检查结果
 */
public static void checkFile(File dataFile) throws Exception {
    // 文件有效性判断
    if (!dataFile.exists()) {
        throw new Exception("文件不存在");
    }
    if (dataFile.isDirectory()) {
        throw new Exception("不是文件");
    }

    // 检查文件后缀
    String path = dataFile.getAbsolutePath();
    String suffix = path.substring(path.lastIndexOf("."));
    if (FILE_TYPE.indexOf(suffix) == -1) {
        throw new Exception("不是文本薄文件");
    }
}

3、读取文本薄。

/**
 * 读取 excelPath所指的excel文件
 *
 * @param excelPath excel文件路径
 * @param sheetIndex 文本簿索引
 * @return
 */
public static List<Map<String, String>> readExcel(String excelPath, int sheetIndex) throws Exception {
    List<Map<String, String>> dataList = new ArrayList<>();

    File dataFile = new File(excelPath);
    // 检查文件
    checkFile(dataFile);

    XSSFWorkbook workbook = new XSSFWorkbook(dataFile);// 获取数据到工作簿
    if (sheetIndex < 0 || sheetIndex >= workbook.getNumberOfSheets())
        throw new Exception("此文本薄条目不存在");
    XSSFSheet sheet = workbook.getSheetAt(sheetIndex);// 获取第n张表

    XSSFRow titleRow = sheet.getRow(0);// 标题行
    for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {// 数据从第二行开始
        Map<String, String> dataMap = new HashMap<>();

        XSSFRow dataRow = sheet.getRow(i);// 数据行
        if (dataRow == null) // 排除空行(当当行所有列全为空时,此行不存在)
            continue;
        if (isValidRow(dataRow)) // 排除无效行
            continue;

        for (int j = 0; j < dataRow.getPhysicalNumberOfCells(); j++) {
            XSSFCell titleCell = titleRow.getCell(j);// 表头
            XSSFCell dataCell = dataRow.getCell(j);// 数据
            dataMap.put(titleCell.getStringCellValue(), getStringCellValue(dataCell));
        }
        dataList.add(dataMap);
    }

    return dataList;
}

4、判断是否是无效行。

/**
 * 判断数据行是否有效
 *
 * @param dataRow 数据行
 * @return
 */
public static boolean isValidRow (XSSFRow dataRow) {
    boolean isValid = true;

    // 若列无内容,则此列不存在
    XSSFCell cell0 = dataRow.getCell(0);// 若第一列有内容,视为有效
    if (cell0 != null)
        isValid = false;

    return isValid;
}

5、获取单元格数据。

/**
 * 根据cell值类型获取值
 *
 * @param cell 文档列
 * @return
 */
public static String getStringCellValue(XSSFCell cell) {
    if (cell == null) {
        return "";
    }
    if (cell.getCellType() == CellType.NUMERIC) {
        return cell.getNumericCellValue() + "";
    } else {
        return cell.getStringCellValue();
    }
}

本文完结。

posted @ 2024-04-19 18:58  进步·于辰  阅读(166)  评论(0编辑  收藏  举报