我正在使用arraylist从Excel工作表中收集产品的参考ID。我正在使用POI。问题是我不想在我的arraylist中包含空白单元格。这是我的代码:
public static ArrayList<String> extractExcelContentByColumnIndex()
{
ArrayList<String> columnData=null;
try
{
FileInputStream fis=new FileInputStream(excel_path);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheetname);
Iterator<Row> rowIterator=sh.iterator();
columnData=new ArrayList<>();
while(rowIterator.hasNext())
{
Row row=rowIterator.next();
Iterator<Cell> cellIterator=row.cellIterator();
while(cellIterator.hasNext())
{
Cell cell=cellIterator.next();
if((row.getRowNum()>=3) && (row.getRowNum()<=sh.getPhysicalNumberOfRows()))
{
if(cell.getColumnIndex()==3)// column under watch
{
columnData.add(cell.getStringCellValue());
Collections.sort(columnData);
}
}
}
}
fis.close();
}
catch(Exception e)
{
e.printStackTrace();
}
System.err.println("DL BoM = "+columnData);
return columnData;
}
输出是:
DL BoM = [, , , , , , 03141, 03803, 08002, 08012, 08817, 13124, A9C22712, A9N21024, A9N21027, A9N21480]
答案 0 :(得分:3)
POI文档为该特定主题提供了一些有用的信息。
遍历细胞,控制缺失/空白细胞
在某些情况下,在迭代时,您需要完全控制缺失的方式 或处理空白行和单元格,您需要确保访问 每个单元格,而不仅仅是文件中定义的单元格。 (CellIterator 只返回文件中定义的单元格,主要是那些 有价值或样式,但它取决于Excel)。
在这些情况下,您应该获取第一列和最后一列 一行的信息,然后调用getCell(int,MissingCellPolicy) 获取单元格。使用MissingCellPolicy控制空白或null 处理细胞。
// Decide which rows to process int rowStart = Math.min(15, sheet.getFirstRowNum()); int rowEnd = Math.max(1400, sheet.getLastRowNum()); for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) { Row r = sheet.getRow(rowNum); if (r == null) { // This whole row is empty // Handle it as needed continue; } int lastColumn = Math.max(r.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT); for (int cn = 0; cn < lastColumn; cn++) { Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL); if (c == null) { // The spreadsheet is empty in this cell } else { // Do something useful with the cell's contents } } }
来源:http://poi.apache.org/spreadsheet/quick-guide.html#Iterator
答案 1 :(得分:1)
在获取单元格值之前..检查它是否为空
if(cell.getColumnIndex()==3)// column under watch
{
if(cell.getStringCellValue().Trim() != "")
{
columnData.add(cell.getStringCellValue());
}
Collections.sort(columnData);
}