写入Excel文件时获取空指针异常

时间:2018-06-19 11:22:56

标签: nullpointerexception automated-tests

在写入Excel文件时获取Null Pointer Exception

public static void setCellData(String Result,  int RowNum, int ColNum) throws Exception {

        try{

                Rw  = ExcelWSheet.createRow(RowNum);

                Cell = Rw.getCell(ColNum, null);

                if (Cell == null) {

                    Cell = Rw.createCell(ColNum);

                    Cell.setCellValue(Result);

                    } else {

                        Cell.setCellValue(Result);

                    }
           FileOutputStream fileOut = new FileOutputStream(Path_TestData + File_TestData);

                    ExcelWBook.write(fileOut);

                    fileOut.flush();

                    fileOut.close();

                    }catch(Exception e){

                        throw (e);

                }

并从另一个类传递参数

File.setCellData("Pass", 2, 2);

这将引发异常错误为Null Pointer Exception。 我已经使用createRow()而不是getRow()的方法来避免空值,并且我的excel有数据,但仍然出现错误。

任何人都可以帮助解决此错误吗?

1 个答案:

答案 0 :(得分:0)

请查看下面的代码并尝试。 希望对您有帮助。

public static void setCellData(String Result,  int RowNum, int ColNum) throws Exception {

        try{
			
					//Blank workbook
					XSSFWorkbook workbook = new XSSFWorkbook();

					//Create a blank sheet
					XSSFSheet sheet = workbook.createSheet("Employee Data");
					XSSFSheet ExcelWSheet = sheet;
					XSSFCell Cell;
					XSSFRow Row;
					Row  = ExcelWSheet.createRow(RowNum);

					Cell = Row.getCell(ColNum, org.apache.poi.ss.usermodel.Row.RETURN_BLANK_AS_NULL);

					if (Cell == null) {

						Cell = Row.createCell(ColNum);

						Cell.setCellValue(Result);

						} else {

							Cell.setCellValue(Result);

						}

					FileOutputStream out = new FileOutputStream(new File("Done.xlsx"));
					workbook.write(out);
					out.close();
					System.out.println("sreeraj done the code");

                    }catch(Exception e){

                        throw (e);

                }