如何从列表中收集Excel中的引用

我正在使用arraylist从Excel工作表中收集产品的参考ID。 我正在使用POI。 问题是我不想在我的数组列表中包含空白单元格。 这是我的代码:

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] 

POI文档为该特定主题提供了一些有用的信息。

迭代单元格,控制缺失/空白单元格

在某些情况下,迭代时需要完全控制如何处理缺失或空白的行和单元格,并且需要确保访问每个单元格,而不仅仅是访问文件中定义的单元格。 (CellIterator只会返回文件中定义的单元格,这些单元格主要是那些带有值或样式的单元格,但它依赖于Excel)。

在这种情况下,您应该获取行的第一列和最后一列信息,然后调用getCell(int,MissingCellPolicy)来获取单元格。 使用MissingCellPolicy来控制如何处理空白或空单元格。

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

在获取单元格值之前,检查它是否不为空

  if(cell.getColumnIndex()==3)// column under watch { if(cell.getStringCellValue().Trim() != "") { columnData.add(cell.getStringCellValue()); } Collections.sort(columnData); }