0

I would like to write to a cell on sheet 2, but the operation errors and I get this message :

Exception in thread "main" java.lang.NullPointerException at Testnextsheet.Testnextsheet.main(Testnextsheet.java:43)

public static void main(String[] args) throws IOException{
    try{
        FileInputStream files = new FileInputStream(new File("d:\\Materi\\Selenium\\Projects\\Excel\\Book1.xlsx"));
        XSSFWorkbook workbook = new XSSFWorkbook(files);
        //----Sheet 1-------------------------------------//
        XSSFSheet sheet1 = workbook.getSheet("Sheet1");
        //---sheet 2--------------------------------------//
        XSSFSheet sheet2 = workbook.getSheet("Sheet2");

            //-----------write text to sheet 2------------------------//    
            sheet2.getRow(3).getCell(2).setCellValue("Test");


        FileOutputStream fout= new FileOutputStream(new File("d:\\Materi\\Selenium\\Projects\\Excel\\Book1.xlsx"));
        workbook.write(fout);
        workbook.close();
        files.close();
    }
    catch(FileNotFoundException fnfe){
        fnfe.printStackTrace();
    }catch(IOException ioe){
        ioe.printStackTrace();
    }
}

1 Answer 1

2

The sheet2 object,which is a TreeMap is empty in the beginning.You need to create a row, then cell and then set the value, something like below-

sheet2.createRow(2).createCell(1).setCellValue("Test");

In your case,sheet2.getRow(3) will throw NullPointerException.

The suggested way would be to iterate the XSSFWorkbook object to access the XSSFSheet and then create as many row and cell as you want and keep on setting the values.

Sign up to request clarification or add additional context in comments.

2 Comments

but i found new problem thas the border in existing will gone
Could you please be more specific? if possible share the code snippet too..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.