gpt4 book ai didi

java - Row row = sheet.getRow(row Number) 即使 Excel 工作表中存在行,也会返回 java.lang.nullpointerexception。我正在使用 Apache POI

转载 作者:行者123 更新时间:2023-12-04 21:07:49 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What is a NullPointerException, and how do I fix it?

(12 个回答)


5年前关闭。




编辑:我正在使用此代码读取 Excel 表的行和列。但是标有双星的行会引发异常(java.lang.nullpointer 异常)。除此之外,我还想将在两者之间找到的空列转换为空白列。请帮忙。

显而易见,有 2 个循环,一个用于行,一个用于列。 Niehter 正在读取该行,也没有解决空白单元格问题。

public void read(String filePath) throws NullPointerException {

try {
FileInputStream file = new FileInputStream(new File(filePath));
System.out.println("going to create Workbook object to read excel row wise");// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
System.out.println("going to create object sheet to read excel row wise");
XSSFSheet sheet = workbook.getSheetAt(0); //extracts the first sheet of excel
System.out.println("Running row iterator to read excel row wise");

for (int rowNumber = sheet.getFirstRowNum(); rowNumber <= sheet.getLastRowNum(); rowNumber++) {
if (rowNumber == sheet.getFirstRowNum())// this row was skipped as it was header row.
{
System.out.println("skipping first row");
continue;
}
this.rowconcat = ""; // all values of perticular row will be concatinated in this variable.
this.flag = 0;

if (sheet.getRow(rowNumber) == null) {
System.out.println("row detected null");
} else {
// The row has data
System.out.println("row no inside else==="+rowNumber);
**Row row = sheet.getRow(rowNumber);** //This line here throws null pointer exception.
for (int cellNumber = row.getFirstCellNum(); cellNumber <= row.getLastCellNum(); cellNumber++) {
Cell cell = row.getCell(cellNumber);
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
this.flag = 1; // set to 1 to indicate blank cell but this also doesn't work
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(" "); //inserting space in cell after converting its type to String.
this.rowconcat = this.rowconcat + cell.getStringCellValue() + "~";
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
this.rowconcat = this.rowconcat + cell.getStringCellValue() + "~";
}
}
}
}
}//try block closure
catch(Exception e){
//autogenerated
}
} // function closure

最佳答案

我推荐 JXL 库更好的 appache 之一,我已经使用它很长时间了。它唯一的小问题是它只适用于 xls 而不是 xlsx(如果到目前为止还没有发生更新!)。

有一个小例子:

File xlsFile;
public void manageData ()
{
Workbook w;
try {
w = Workbook.getWorkbook(xlsFile);
// Get the first sheet
Sheet sheet = w.getSheet(0);
int j = 1;
//Begin from the second row
while (j < sheet.getColumns()) {
//staff
Cell infoCell = sheet.getCell(j, 4);
System.out.println(infoCell.getContents());
}
catch (Exception e)
{
}
}

关于java - Row row = sheet.getRow(row Number) 即使 Excel 工作表中存在行,也会返回 java.lang.nullpointerexception。我正在使用 Apache POI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40504099/

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