当在JAVA中调用一个方法将一个字符串写入Excel表格时,在线程 "main "中出现java.lang.NullPointerException异常。错误如下
线程 "main "中出现异常 java.lang.NullPointerException at ManualVolteCxCreation.ExcelDataReader.writeExcelTestResult(ExcelDataReader.java:51)
从主类中调用writeExcelTestResult方法,如下图。
excelDataReader.writeExcelTestResult(startRowIndex, "There are already connections with");
Excel Data Reader类有构造函数,其中初始化excel文件、excel工作簿和excel工作表,以及读取excel数据和写入excel文件第7列的两个方法。Excel数据读取器类如下。
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelDataReader {
ConfigReader configReader = new ConfigReader();
File testFilePath;
FileInputStream fis;
XSSFWorkbook volteConnections;
XSSFSheet testDataFile;
XSSFRow rowTestData;
public ExcelDataReader() {
try {
testFilePath = new File(configReader.readPropertyValue("excel"));
fis = new FileInputStream(testFilePath);
// Finds the workbook instance for XLSX file
volteConnections = new XSSFWorkbook(fis);
// Return first sheet from the XLSX workbook
testDataFile = volteConnections.getSheetAt(0);
} catch (Exception e) {
e.printStackTrace();
}
}
public XSSFRow readExcelRowTestData(int rowIndex) {
rowTestData = testDataFile.getRow(rowIndex);
return rowTestData;
}
public void writeExcelTestResult(int rowIndex, String testResult) {
testDataFile.getRow(rowIndex).getCell(7).setCellValue(testResult);
}
}
我调试了一下,想看看问题出在哪里,但发现每个变量都被初始化了,如下图所示。
那么有什么建议可以解决这个问题吗?
你只需要先创建单元格,然后调用setCellValue方法。
为了保存文件,你还需要FileOutputStream对象,所以你可以修改writeExcelTest方法。
所以你可以修改writeExcelTestResult方法,如下所示。
public void writeExcelTestResult(int rowIndex, String testResult) {
if (cellTestData == null) {
cellTestData = testDataFile.getRow(rowIndex).createCell(7);
}
cellTestData.setCellValue(testResult);
try {
fis.close();
fos = new FileOutputStream(testFilePath);
volteConnections.write(fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}