How to loop through all the rows and cells in an excel file

烈酒焚心 提交于 2019-12-22 03:56:15

问题


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.


回答1:


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




回答2:


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());


来源:https://stackoverflow.com/questions/8424327/how-to-loop-through-all-the-rows-and-cells-in-an-excel-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!