通过提供列位置 POI 来读取选择性列的函数



excel文件中的示例数据,这里的第一行是标题。

Demo1           Demo2           Demo3           Demo4           Demo5           Demo6
DummyText1      DummyText2      DummyText3      DummyText4      DummyText5      DummyText6
DummyText11     DummyText21     DummyText31     DummyText41     DummyText51     DummyText61

下面的代码包含选择性列工作正常,但是对于另一列,我必须再次在 if 条件中添加 cell1.getColumnIndex(( 等等。

for (Cell cell1 : row) {
if (cell1.getColumnIndex() != 1 && cell1.getColumnIndex() != 3) {
continue;
}
}

所以我创建了下面的函数来跳过单元格((;但它没有按预期工作。

for (Cell cell : row) {
skipCells(cell,1,3,6) // this should read only column 1,3 and 6, but it is not working.
String result = getCellData(xssfWorkbook, cell);
System.out.println(result);
}
static void skipCells(Cell cell,int ...cellPosition)
{
for (int i: cellPosition) {
if (cell.getColumnIndex() != i) {
continue;
}
}
}

您只是遍历单元格,什么都不做,将 skipCells 更改为

static void skipCells(Cell cell,int ...cellPosition) {
for (int i: cellPosition) {
if (cell.getColumnIndex() == i) {
break;
}
}
}

或者只是创建一个要阅读的列的列表,并检查列表中是否有该列。

List<Integer> list = Arrays.asList(1, 3, 6);
for (Cell cell : row) {
if (list.contains(cell.getColumnIndex())) {
String result = getCellData(xssfWorkbook, cell);
System.out.println(result);
}
}
while (rows.hasNext())
{
int colNumber = 0;
row=(HSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{colNumber++;
cell=(HSSFCell) cells.next();
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}

switch(colNumber){
case 1:
singleRecord.setXX1(cellValue);
break;
case 2:
singleRecord.setXX2(cellValue);
break;
case 3:
singleRecord.setXX3(cellValue);
break;
case 4:
singleRecord.setXX4(cellValue);
break;
case 5:
singleRecord.setXX5(cellValue);
break;
case 6:
singleRecord.setXX6(cellValue);
break;
default:
System.out.println("--> Invalid column");
}   


}
System.out.println();
}
/////////////////////////////////////
create bean class and add getter/setter properties inside switch case 
you can later add this object to LinkList also and process as you wish

将 skipCells 函数的返回类型更改为 Cell

static Cell skipCells(Cell cell, int... cellPosition){
Cell c = null;
for (int i: cellPosition) {
if (cell.getColumnIndex() != i) {
continue;
}
c = cell;
}
return c;
}
for (Cell cell : row) {
Cell readCell = skipCells(cell, 1, 3, 6)
if(readCell != null ) { // remove null value if any
System.out.println(getCellData(xssfWorkbook, readCell));               
}
}

最新更新