gpt4 book ai didi

java - 空指针异常apache poi

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:50:21 26 4
gpt4 key购买 nike

嗨,我们一直在使用 apache poi 读取我们的 java 程序的 xls 和 xlsx 文件,问题是我们得到空指针异常有两个原因。第一个是我们已经解决的空白单元格,另一个是是当我们选择某个没有任何记录的列时..

我们的程序要求excel文件的路径,然后是文件的具体工作表编号和你要阅读的工作表的具体列号..这是读取xls文件的代码

public void readXLSFile()throws IOException{
InputStream ExcelFileToRead = new FileInputStream(path);
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);


HSSFSheet sheet=wb.getSheetAt(sheetname);
HSSFRow row;
HSSFCell cell;

Iterator rows = sheet.rowIterator();

list1.clear();

while (rows.hasNext())
{
headers.clear();
row=(HSSFRow) rows.next();

// Iterator cells = row.cellIterator();

headers.add("contents");


cnt = cnt+1;

cell = row.getCell(cols);
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
//System.out.println(cell.getStringCellValue()+"(string)");
list.add(cell.getStringCellValue());
d.add(cell.getStringCellValue());
list1.add(new KeyValuePair(cell.getStringCellValue(),""));
}
else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
{
//System.out.println(cell.getNumericCellValue()+"(numeric)");
double num = cell.getNumericCellValue();
String num2 = String.valueOf(num);
list.add(num2);
d.add(num2);
list1.add(new KeyValuePair(num2,""));

}
else if(cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN)
{
//System.out.println(cell.getBooleanCellValue()+"(boolean)");
String bool = String.valueOf(cell.getBooleanCellValue());
list.add(bool);
d.add(bool);
list1.add(new KeyValuePair(bool,""));
}
else
{
//U Can Handel Boolean, Formula, Errors
}


//System.out.println();
}
arrey = list.toArray(new String[list.size()]);
data.add(d);
// System.out.println(data);


model = new DefaultTableModel();
table_1.setModel(model);


table_1.setModel(model);
model.setColumnIdentifiers(new String[] {"row","contents"});

for (KeyValuePair p : list1){


int nor=table_1.getRowCount();

int n2 = nor +1;
n1 = Integer.toString(n2);
// model.addColumn(new String [] {n1});


model.addRow(new String[] {n1,p.key, p.value});


}
// model.addColumn(new String[] {n1});

}

变量 sheetname 是 excel 文件的工作表编号

HSSFSheet sheet=wb.getSheetAt(sheetname);

变量 cols 是你想要阅读的特定列

cell = row.getCell(cols);

我们可以读取每张纸的第一列,也可以读取第二张纸的第二列,但是当我编辑我的测试文件时,程序现在只能读取每张纸的第一列。错误是空指针异常。希望你能帮忙提前谢谢

最佳答案

问题是您从不测试单元格是否为空!

if (cell == null)
{
System.out.println("Cell is Empty in Column:" + cols);

} else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
//code
}

一般来说,在处理 Cell.getCellType() 函数时应该小心,因为空单元格可能是 nullCELL_TYPE_BLANK

关于java - 空指针异常apache poi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18072847/

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