簡體   English   中英

調用方法將字符串寫入 JAVA 中的 Excel 表時,線程“主”java.lang.NullPointerException 中的異常錯誤

[英]Exception in thread “main” java.lang.NullPointerException error when calling a method to write a string into Excel sheet in JAVA

調用方法將字符串寫入 JAVA 中的 Excel 表時,線程“主”java.lang.NullPointerException 出現異常錯誤。 錯誤如下

ManualVolteCxCreation.ExcelDataReader.writeExcelTestResult(ExcelDataReader.java:51) 的線程“主”java.lang.NullPointerException 中的異常

從主 class 調用 writeExcelTestResult 方法,如下所示。

excelDataReader.writeExcelTestResult(startRowIndex, "There are already connections with");

Excel Data Reader class has the constructor in which initialize the excel file, excel workbook and the excel sheet and two methods to read excel data and write to the 7th column of the excel file. Excel 數據讀取器 class 如下。

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 object。

因此,您可以修改 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();
        }         

   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM