簡體   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