gpt4 book ai didi

java - 如何使用 poi 读取 excel 文件中的空单元格以及如何将此空单元格添加到数组列表?

转载 作者:行者123 更新时间:2023-12-03 18:41:52 25 4
gpt4 key购买 nike

    public void readExcel(String fileName)
try
{
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext())
{
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
ArrayList cellStoreVector=new ArrayList();
String header_name = null;
while(cellIter.hasNext())
{
HSSFCell myCell = (HSSFCell) cellIter.next();
// if it is empty cell in my excel file its not added to
// array List
cellStoreVector.add(myCell);
}
cellVectorHolder.add(cellStoreVector);

}
}catch (Exception e)
{
e.printStackTrace();
}
saveToDatabase(cellVectorHolder);
}

public void saveToDatabase(ArrayList array)
{
for (int i=0;i<array.size(); i++)
{
ArrayList cellStoreVector=(ArrayList)array.get(i);
for (int j=0; j < cellStoreVector.size();j++)
{
HSSFCell myCell = (HSSFCell)cellStoreVector.get(j);
String st = myCell.toString();
System.out.println("values "+st);
}
}
}

上面的代码是我读取 excel 文件并将值打印到控制台的示例代码。在这里,我在读取空白单元格时遇到问题,并且此空白单元格未显示在控制台中。所以请给我读取空白单元格的解决方案并在控制台中打印这个空白。

最佳答案

来自 HSSFRow#cellIterator JavaDoc:

Note that the 4th element might well not be cell 4, as the iterator will not return un-defined (null) cells. Call getCellNum() on the returned cells to know which cell they are.

这意味着您必须存储当前和最后一个单元格编号,如果您得到的差异大于 1,则您之间有空白/未定义的单元格,即类似于 int numBlankCells = (curCellNum - lastCellNum) - 1;

另一种方法可能是:

short minColIndex = row.getFirstCellNum();
short maxColIndex = row.getLastCellNum();
for(short colIndex = minColIndex; colIndex < maxColIndex; colIndexx++) {
HSSFCell cell = row.getCell(colIndex);
if(cell == null) {
//blank/undefined cell
}
else {
//defined cell which still could be of type HSSFCell.CELL_TYPE_BLANK or contain an empty string
}
}

关于java - 如何使用 poi 读取 excel 文件中的空单元格以及如何将此空单元格添加到数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5699936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com