问题
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