Skip to content
Advertisement

Update Cell in excel file using Java Apache POI

I’m trying to update an empty cell in an existing excel file using Java ( Apache POI ), here is the code I wrote, I don’t get any errors and the values aren’t changed either .

        FileInputStream file = new FileInputStream(new File("recap.xlsx"));
        
 
        
        XSSFWorkbook workbook = new XSSFWorkbook(file);
         
        
         XSSFSheet sheet = workbook.getSheetAt(0);
         Cell cell = null;
         
       //Retrieve the row and check for null
         XSSFRow sheetrow = sheet.getRow(7);
         if(sheetrow == null){
             sheetrow = sheet.createRow(7);
             System.out.println("its null 1 ");
         }
         //Update the value of cell
         cell = sheetrow.getCell(7);
         if(cell == null){
             cell = sheetrow.createCell(7);
             System.out.println("its null  2 !");
         }
         
         
         cell.setCellValue("Second");

     file.close();

     workbook.close();

I get ” its null 2 ! ” in console .

Any solutions?

Thanks 🙂

Advertisement

Answer

You need to open an output stream and write to the workbook as follows:

file.close();

FileOutputStream outputStream = new FileOutputStream("recap.xlsx");
workbook.write(outputStream);

workbook.close();
outputStream.close();

Also, make sure to close the workbook and the output stream after this write operation.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement