java 如何遍历列以获取 Excel 中的行标记数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33808926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:09:21  来源:igfitidea点击:

How to iterate over columns to get row labeled data in Excel?

javaexcelapache-poi

提问by Madhusudan

I am writing a Java program in which I want to retrieve data which has row headers. My Excel sheet looks like below:

我正在编写一个 Java 程序,我想在其中检索具有行标题的数据。我的 Excel 工作表如下所示:

enter image description here

在此处输入图片说明

I have written a following simple Java code to retrieve values sequentially based on row headers:

我编写了以下简单的 Java 代码来根据行标题顺序检索值:

....
try
    {
    fileSystem = new POIFSFileSystem (inpStrm);

    HSSFWorkbook      workBook = new HSSFWorkbook (fileSystem);
    HSSFSheet         sheet    = workBook.getSheetAt(0);
    int column = 1;
    for(int i = 0;i <=3;i++){

        for(int j = 0;j<=3;j++){
            HSSFRow row = sheet.getRow(j);
            System.out.print(row.getCell(column).getStringCellValue() + "    ");
        }
        System.out.println("");
        column++;
    }
    }
    catch(Exception e){
        e.printStackTrace();
    }
....

And after running code my output comes like below:

运行代码后,我的输出如下所示:

P1    M    C1    Hyderabad    
P2    M    C2    Pune    
P3    F    C3    Pune    
P4    M    C4    Hyderabad 

Now is there any easy and feasible way to do the same for large Excel sheets (50 row headers)?

现在是否有任何简单可行的方法可以对大型 Excel 工作表(50 行标题)执行相同操作?

If I use the POGO class having above four properties then how can I get list of objects with values from Excel?

如果我使用具有以上四个属性的 POGO 类,那么如何从 Excel 获取具有值的对象列表?

回答by winklerrr

Now is there any easy and feasible way to do the same for large Excel sheets (50 row headers)?

现在是否有任何简单可行的方法可以对大型 Excel 工作表(50 行标题)执行相同操作?

You could use the method sheet.getLastRowNum()as condition in your for loop to iterate over all rows and the method row.getLastCellNum()in a second loop to iterate over all cells in a specific row.

您可以sheet.getLastRowNum()在 for 循环中使用该方法作为条件来迭代所有行,并row.getLastCellNum()在第二个循环中使用该方法来迭代特定行中的所有单元格。

for(int rowNumber = 0; rowNumber < sheet.getLastRowNum(); rowNumber++) {
    HSSFRow row = sheet.getRow(rowNumber);

    for(int columnNumber = 0; columnNumber < row.getLastCellNum(); columnNumber++) {
        HSSFCell cell = row.getCell(columnNumber);
        if(cell != null) {
            // do something with the cell
        }
}

Important:The code above loops first through each column and then through each row.

重要提示:上面的代码首先遍历每一列,然后遍历每一行。

回答by Suresh Gupta

Try following

尝试以下

for (Cell cell : sheet.getRow(i )) {

    //your logic
}