2

我有一个 2 行 5 列的 excel。现在我手动输入代码以从第一行获取值。我怎样才能迭代这个过程?

下面是excel中第一行的代码。从第二行开始,我不知道该怎么做......我想逐行迭代。

Workbook workbook = Workbook.getWorkbook(new File(
                               "\\C:\\users\\a-4935\\Desktop\\DataPool_CA.xls"));
Sheet sheet = workbook.getSheet("Sheet1");
System.out.println("Reached to Sheet");
Cell a = sheet.getCell(2,1);
Cell b = sheet.getCell(3,1);
Cell c = sheet.getCell(4,1);
Cell d = sheet.getCell(5,1);
Cell e = sheet.getCell(6,1);
Cell f = sheet.getCell(7,1);
Cell g = sheet.getCell(8,1);
Cell h = sheet.getCell(9,1);
Cell i = sheet.getCell(10,1);

String uId              =   a.getContents();
String deptFromDat      =   b.getContents();
String deptToDate       =   c.getContents();
String dept1            =   d.getContents();
String arrival1         =   e.getContents();
String eihon1           =   f.getContents();
String branchCode1      =   g.getContents();
String userType1        =   h.getContents();
String sessionId1       =   i.getContents();
4

3 回答 3

10

使用下面的代码迭代数据表的所有行:

Sheet sheet = workbook.getSheet("Sheet1");
for (Row row : sheet) {
    for (Cell cell : row) {
        //your logic
    }
}

或者,或者,使用以下代码:

Sheet sheet = workbook.getSheet("Sheet1");
for (int i = 0; i < 2; i++) {
    Row row = sheet.getRow(i);
    if(row == null) {
        //do something with an empty row
        continue;
    }
    for (int j = 0; j < 5; j++) {
        Cell cell = row.getCell(j);
        if(cell == null) {
            //do something with an empty cell
            continue;
        }
        //your logic
    }
}
于 2013-04-25T13:19:16.550 回答
1
for (int i = 0; i <= sheet.getLastRowNum (); ++i) {
        row=(Row) sheet.getRow(i);
        Iterator<Cell> cells = row.cellIterator();
        while (cells.hasNext())
        { .....

您可以使用上面的代码来迭代所有行和所有单元格

于 2015-08-08T07:27:12.783 回答
0

您只需将 1 更改为行号,并使用 for 循环。根据您的代码,您可以执行以下操作,例如:

for(int i=0; i<number; i++)
{

            Cell a = sheet.getCell(2,i);
            Cell b = sheet.getCell(3,i);
            Cell c = sheet.getCell(4,i);
...

}

或者更好地将 Cell 声明移出 for 循环,这是更好的做法。

Cell a,b, c...; 

for(int i=0; i<number; i++)
{

             a = sheet.getCell(2,i);
             b = sheet.getCell(3,i);
             c = sheet.getCell(4,i);
...

}
于 2013-04-25T13:19:46.330 回答