如何在java中进行excel的单元迭代
我有一个2行5列的excel。现在我手动输入代码,从第一行获取值。如何迭代该过程 下面是excel中第一行的代码。从第二排开始,我不知道该怎么做。。。我想迭代一行又一行如何在java中进行excel的单元迭代,java,apache-poi,Java,Apache Poi,我有一个2行5列的excel。现在我手动输入代码,从第一行获取值。如何迭代该过程 下面是excel中第一行的代码。从第二排开始,我不知道该怎么做。。。我想迭代一行又一行 Workbook workbook = Workbook.getWorkbook(new File( "\\C:\\users\\a-4935\\Desktop\\DataPool_CA.xls")); Sheet sheet = workbook.getSheet(
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();
使用以下代码迭代数据表的所有行:
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
}
}
Sheet Sheet=workbook.getSheet(“Sheet1”);
对于(int i=0;i<2;i++){
Row Row=sheet.getRow(i);
if(行==null){
//用空行做某事
继续;
}
对于(int j=0;j<5;j++){
Cell Cell=row.getCell(j);
if(单元格==null){
//用空电池做点什么
继续;
}
//你的逻辑
}
}
您只需将1更改为行号,并使用for循环即可。
根据您的代码,您可以执行以下操作:。
对于exmaple:
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);
...
}
for(int i=0;ifor(int i=0;对于后者,请注意getRow或getCell可能返回null!这完全是@Gagravarr的说法,否则下一个问题将是“为什么我有一个NPE?”。尽管如此,由于OP提到的文件应该填充2*5个单元格,我没有包含检查。但为了将来的读者,值得包含这些检查丁格他们。谢谢!应该有和每个文件将有很少是相同的东西…!只能迭代数组或java.lang.Iterable的实例此错误为coming@user2314399你把1换成i了吗?
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);
...
}
for (int i = 0; i <= sheet.getLastRowNum (); ++i) {
row=(Row) sheet.getRow(i);
Iterator<Cell> cells = row.cellIterator();
while (cells.hasNext())
{ .....