java Excel单元格如何使用Apache POI处理空数据?

hl0ma9xz  于 2023-05-27  发布在  Java
关注(0)|答案(2)|浏览(264)

使用apache poi,我制作了Excel数据阅读逻辑。但是,由于没有处理空值,所以输出数据不正确。我该怎么办?

Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();

            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();

                switch (cell.getCellType()) {

                    case NUMERIC:
                    System.out.print((int) cell.getNumericCellValue() + "\t"); 
                    break;
                    case STRING:      
                    System.out.print(cell.getStringCellValue() + "\t");
                    break;
                }
            }
            System.out.println();
deyfvvtc

deyfvvtc1#

你需要检查单元格中的空值。

Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();

        Iterator<Cell> cellIterator = row.cellIterator();
        
        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();

            if(cell==null) {
               System.out.print("nothing"+ "\t");
               continue;
            }
            switch (cell.getCellType()) {

                case NUMERIC:
                System.out.print((int) cell.getNumericCellValue() + "\t"); 
                break;
                case STRING:      
                System.out.print(cell.getStringCellValue() + "\t");
                break;
            }
        }
        System.out.println();
ws51t4hk

ws51t4hk2#

public static void readXLSFileWithBlankCells() {
    try {
        InputStream ExcelFileToRead = new FileInputStream(EXCEL_FILE);
        HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);

        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow row;
        HSSFCell cell;

        Iterator rows = sheet.rowIterator();

        while (rows.hasNext()) {
            row = (HSSFRow) rows.next();
            
            for(int i=0; i<row.getLastCellNum(); i++) {
                cell = row.getCell(i, Row.CREATE_NULL_AS_BLANK);
                System.out.print(cell.toString()+" ");
            }
            System.out.println();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

感谢@madan712(https://gist.github.com/madan712/5611191
但如果总共有13个单元格,但第13个单元格不包含值,则row.getLastCellNum()仍然错过最后一个单元格
我的解决方案是在一个全局字段中存储lastCellNum的值,基于表的头部,如final int totalCol = headerRow.getLastCellNum(),那么单元格循环将是for(int i=0; i<totalCol; i++)

相关问题