POI读取excel中数据


直接贴代码了,包括对于合并单元格的处理。

 

    public String[][] readSheet(Integer sheetId) {

        XSSFSheet sheet = workbook.getSheetAt(sheetId);

        int rowCount = sheet.getPhysicalNumberOfRows();
        String[][] data = new String[rowCount][];
        // 1. 遍历一遍数据
        for (int i = 0; i < rowCount; i++) {
            XSSFRow row = sheet.getRow(i);
            int colCount = row.getPhysicalNumberOfCells();
            data[i] = new String[colCount];

            for (int j = 0; j < colCount; j++) {
                XSSFCell cell = row.getCell(j);
                String value;
                if (cell != null && StringUtils.isNotBlank(value = cell.getStringCellValue())) {
                    data[i][j] = value;
                }
            }
        }


        // 2.解析所有的联合空格
        List<CellRangeAddress> list = sheet.getMergedRegions();
        for (CellRangeAddress cellAddresses : list) {
            int startRow = cellAddresses.getFirstRow();
            int endRow = cellAddresses.getLastRow();
            int startCol = cellAddresses.getFirstColumn();
            int endCol = cellAddresses.getLastColumn();

            // 2.1 起始位置数据
            String value = data[startRow][startCol];

            // 2.2 遍历所有位置数据
            if (StringUtils.isNotBlank(value)) {
                for (int i = startRow; i <= endRow; i++) {
                    for (int j = startCol; j <= endCol; j++) {
                        data[i][j] = value;
                    }
                }
            }
        }
        return data;
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM