Java 如何使用 Apache POI 浏览工作簿的工作表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20340915/
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-08-13 01:11:24  来源:igfitidea点击:

How to go though the sheets of a Workbook with Apache POI?

javaexcelapache-poi

提问by Kotsor

I am a real newb programer trying to make a small java program that edits spreadsheets for a friend using Apache Poi. Currently I go through the excel file using this code:

我是一个真正的新手程序员,试图制作一个使用 Apache Poi 为朋友编辑电子表格的小型 Java 程序。目前我使用以下代码浏览 excel 文件:

Sheet paxgs = rs1.getSheetAt(0); 
for (Row row : paxgs) {
       Cell secCell = row.getCell(1);
       Cell firstCell = row.getCell(0);
       if (firstCell!=null && firstCell.getCellType()==firstCell.CELL_TYPE_STRING)
}

The problem is that I don't know the exact number of sheets that the excel file is going to have. I tried :

问题是我不知道 excel 文件将拥有的确切工作表数量。我试过 :

Workbook rs1 = WorkbookFactory.create(new FileInputStream(filename));    
for (Sheet sheet : rs1)

but it didn't work so I was wondering if there is any way to go through all the sheet of a workbook.

但它没有用,所以我想知道是否有任何方法可以浏览工作簿的所有工作表。

采纳答案by rgettman

A Workbookdoesn't implement Iterable<Sheet>like a Sheetimplements Iterable<Row>, so you can't use an "enhanced" for loop. But you can loop through the Sheetobjects yourself, with a traditional for loop. Use getNumberOfSheets()to find the number of sheets, and getSheetAtto retrieve the individual Sheetobjects.

AWorkbook不像 implementsIterable<Sheet>那样Sheet实现Iterable<Row>,因此您不能使用“增强型” for 循环。但是您可以Sheet使用传统的 for 循环自己循环遍历对象。使用getNumberOfSheets()找张数,并getSheetAt取回个人Sheet物品。

for (int i = 0; i < workbook.getNumberOfSheets(); i++)
{
    Sheet sheet = workbook.getSheetAt(i);
    // Process your sheet here.
}

回答by James Anderson

The workbook contains a protected field "_sheets" which is of type java.util.List so:-

该工作簿包含一个受保护的字段“_sheets”,其类型为 java.util.List,因此:-

 rs1._sheets.size();

Should get you the number of sheets. You should also be able to iterate through this list.

应该给你张数。您还应该能够遍历此列表。