本文介绍了在 Apache POI 中跳过空白 Excel 单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Apache POI 的新手,但我想要做的是通过 Excel 文件 (.xls) 读取并将其放入 ArrayList 进行存储,以便我以后可以进行操作.我可以得到整张表,但我的问题是:我得到了整个 dang 表(~54183 行).

I'm new to the Apache POI, but what I want to do is read though an Excel file (.xls) and put that into a ArrayList to store so that I can later manipulate. I can get the whole sheet, but my problem is just that: I get the whole dang sheet (~54183 rows).

我想跳过类型为 3 的空白单元格.出于某种原因,当我 system.out.print ArrayList 时,它包含所有空白单元格.

I want to skip over the cells that are blank, which is of type 3. For some reason, when I system.out.print the ArrayList, it has all the blank cells in there.

有没有办法跳过这些而不将它们添加到我正在尝试创建的 ArrayList 中?

Is there a way to skip over those and not add them to the ArrayList I'm trying to create?

我有以下代码:

public ArrayList readExcelFile(String filePath) throws IOException {
    ArrayList cellVectorHolder = new ArrayList();
    try {
        FileInputStream inputFile = new FileInputStream(filePath);
        POIFSFileSystem myFileSystem = new POIFSFileSystem(inputFile);
        HSSFWorkbook wkbk = new HSSFWorkbook(myFileSystem);
        wb = wkbk;
        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
            HSSFSheet wkSheet = wkbk.getSheetAt(i);
            for (Row row : wkSheet) {
                ArrayList cellVector = new ArrayList();
                for (Cell cell : row) {
                    if(cell.getCellType() != 3){
                        cellVector.add(cell);
                    }
                }
                cellVectorHolder.add(cellVector);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return cellVectorHolder;
}

不要介意 ArrayList 名称...我一直在使用 Vectors,直到我最终发现它们从 1.2 或类似的版本开始贬值.

Don't mind the ArrayList names...I was using Vectors until I finally discovered they were depreciated since 1.2 or something like that.

推荐答案

在将单元格添加到列表之前,您可以检查单元格值.类似的东西:

Before adding the cell to the List, you can check the cell value. Something like:

if (cell.getStringCellValue() != null &&  cell.getStringCellValue().length() != 0) {
    cellVector.add(cell);
}

只有在有内容时才添加单元格.

You only add the cell if there is some content.

这篇关于在 Apache POI 中跳过空白 Excel 单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 21:34