How to loop through all the rows and cells in an e

2020-08-15 04:01发布

I want to use foreach to iterate through all the cells in my excel file in order to set a single foreground color. This is what I have so far.

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Sheet1");
sheet = wb.getSheetAt(0);

for (HSSFRow myrow : sheet){
    for (HSSFCell mycell : myrow){
        //set foreground color here
    }
}

The problem is for the statements for (HSSFRow myrow : sheet) and for (HSSFCell mycell : myrow) I am getting:

Can only iterate over an array or an instance of java.lang.Iterable

I checked HSSFSheet and HSSFRow - they implement java.lang.Iterable(Row) and java.lang.Iterable(Cell) respectively.

3条回答
Deceive 欺骗
2楼-- · 2020-08-15 04:47

You can also do this:

for ( int r=0; r < sheet.getPhysicalNumberOfRows(); r++ )
{
    Row row = sheet.getRow(r);

    for ( int c=0; c < sheet.getRow(0).getPhysicalNumberOfCells(); c++ )
    {
        // do stuff to each cell here...
    }
}
查看更多
冷血范
3楼-- · 2020-08-15 04:53

Try this. It compiles ok

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Sheet1");
sheet = wb.getSheetAt(0);

for (Row myrow : sheet) {
    for (Cell mycell : myrow) {
        //set foreground color here
    }
}

I am using POI 3.7 Stable

查看更多
虎瘦雄心在
4楼-- · 2020-08-15 04:55

Please consider using stream for a more declarative style iteration:

Workbook wb = WorkbookFactory.create(new FileInputStream("filename.xlsx"));    
Sheet sheet = wb.getSheetAt(0);

StreamSupport.stream(sheet.spliterator(), false)
         .filter(...)
         .map(...)
         .collect(Collectors.toList());
查看更多
登录 后发表回答