我正在使用 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 文档提供了有关该特定主题的一些有用信息。
Iterate over cells, with control of missing / blank cells
In some cases, when iterating, you need full control over how missing or blank rows and cells are treated, and you need to ensure you visit every cell and not just those defined in the file. (The CellIterator will only return the cells defined in the file, which is largely those with values or stylings, but it depends on Excel).
In cases such as these, you should fetch the first and last column information for a row, then call getCell(int, MissingCellPolicy) to fetch the cell. Use a MissingCellPolicy to control how blank or null cells are handled.
// 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
关于java - 如何从 Excel 中的数组列表中收集引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33776087/