gpt4 book ai didi

java - 写入 Excel 文件时出现空指针异常

转载 作者:行者123 更新时间:2023-12-01 09:00:31 25 4
gpt4 key购买 nike

尝试写入 Excel 文件时获取 Null pointer Exception来自线路sheet.createRow(1).createCell(5).setCellValue("Pass");不明白为什么会出现这个错误:(

package com.qtpselenium.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.qtpselenium.util.Xls_Reader;

public class ReturnTestCaseResult {

public static void main(String[] args) {

String path =System.getProperty("user.dir") + "\\src\\com\\qtpselenium\\xls\\suiteA.xlsx";
/* Xls_Reader xlsr = new Xls_Reader(System.getProperty("user.dir") + "\\src\\com\\qtpselenium\\xls\\suiteA.xlsx");
ReportDataSetResult(xlsr, "TestCaseA1", 3, "Pass" , path);*/

ReportDataSetResult("TestCaseA1", path);
}


public static void ReportDataSetResult( String TestCaseName , String path){


System.out.println(TestCaseName +"----"+ path);
try {
FileInputStream fileinp = new FileInputStream(path);
XSSFWorkbook workbook = new XSSFWorkbook();

XSSFSheet sheet = workbook.getSheet(TestCaseName);

sheet.createRow(1).createCell(5).setCellValue("Pass");

FileOutputStream fileout = new FileOutputStream(path);
workbook.write(fileout);
fileout.close();



} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}




}

}

最佳答案

您已使用无参数构造函数来创建工作簿:

XSSFWorkbook workbook = new XSSFWorkbook();

这意味着工作簿中没有工作表。这意味着您的工作表变量将为空。我认为您想要将 FileInputStream fileinp 传递到工作簿构造函数中,以便它从现有文件中读取?

XSSFWorkbook workbook = new XSSFWorkbook(fileinp);

否则,您需要在工作簿中创建一个名为 TestCaseName 的工作表,然后才能开始向其中添加行。

关于java - 写入 Excel 文件时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41709972/

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