繁体   English   中英

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

[英]While Writing into Excel file getting Null pointer Exception

在尝试写入 Excel 文件时,从行sheet.createRow(1).createCell(5).setCellValue("Pass");获取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();
        }
        
          
        
        
    }
    
}
    

您已使用 no arg 构造函数来创建工作簿:

XSSFWorkbook workbook = new XSSFWorkbook();

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

XSSFWorkbook workbook = new XSSFWorkbook(fileinp);

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

也许,row(1) 为空,您可以尝试先创建它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM