如何遍历excel文件中的所有行和单元格

时间:2011-12-07 23:46:07

标签: java apache-poi

我想使用foreach迭代excel文件中的所有单元格以设置单个前景色。这是我到目前为止所做的。

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
    }
}

我遇到的问题是for (HSSFRow myrow : sheet)for (HSSFCell mycell : myrow)

  

只能遍历数组或java.lang.Iterable

的实例

我检查了HSSFSheetHSSFRow - 他们分别实施了java.lang.Iterable(Row)java.lang.Iterable(Cell)

4 个答案:

答案 0 :(得分:22)

试试这个。它编译好了

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
    }
}

我正在使用POI 3.7 Stable

答案 1 :(得分:4)

请考虑使用stream进行更具说明性的样式迭代:

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

StreamSupport.stream(sheet.spliterator(), false)
         .filter(...)
         .map(...)
         .collect(Collectors.toList());

答案 2 :(得分:0)

您也可以这样做:

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 :(得分:0)

这是我以最简单的方式保持事物的方式 - 遍历所有行和列:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadExcelTest {

    @SuppressWarnings("resource")
    public static void main(String[] args) throws IOException {
        
        // Read input file
        FileInputStream fis = new FileInputStream("sample.xlsx");

        XSSFWorkbook wbook = new XSSFWorkbook(fis);
        XSSFSheet sheet = wbook.getSheetAt(0);
        
        // formatter for all your data to string (in this example) from date/number etc
        DataFormatter formatter = new DataFormatter();
        
        // Below code is self explanatory

        Iterator<Row> rowIterator = sheet.iterator();

        while (rowIterator.hasNext()) {

            Row row = rowIterator.next();
            // Since I needed only five columns, I hardcoded the column numbers
            System.out.println(formatter.formatCellValue(row.getCell(0)));
            System.out.println(formatter.formatCellValue(row.getCell(1)));
            System.out.println(formatter.formatCellValue(row.getCell(2)));
            System.out.println(formatter.formatCellValue(row.getCell(3)));
            System.out.println(formatter.formatCellValue(row.getCell(4)));

        }

    }
}

免责声明:我使用了截至日期的最新 POI:

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.0.0</version>
    </dependency>