【问题标题】:While Writing into Excel file getting Null pointer Exception写入 Excel 文件时出现空指针异常
【发布时间】:2020-07-20 03:52:36
【问题描述】:

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

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();
        }
        
          
        
        
    }
    
}
    

【问题讨论】:

    标签: java apache-poi


    【解决方案1】:

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

    XSSFWorkbook workbook = new XSSFWorkbook();
    

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

    XSSFWorkbook workbook = new XSSFWorkbook(fileinp);
    

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-28
        • 1970-01-01
        • 2020-03-19
        • 1970-01-01
        • 1970-01-01
        • 2013-04-10
        相关资源
        最近更新 更多