Search code examples
javaexcelapachecellsavechanges

Adding data to a new cell in excel without deleting the previous cell


When I try to add new data to this xls file, I lose my previous data. How can I add new information to new cells and save it?

My code is Apache POI:

Workbook w = new HSSFWorkbook();

Sheet s = w.createSheet("new");   

Cell a = s.createRow(0).createCell(0);    
Cell b = s.createRow(0).createCell(1);    
a.setCellValue(jTextField1.getText());    

try {
    FileOutputStream f = new FileOutputStream("C://NEW.xls");
    w.write(f);
    w.close();`
} catch (Exception e) {

}

Solution

  • You need to input the sheet (using InputStream), add the record, and then save again. Right now you're creating a new Workbook Object and then writing it with the OutputStream which will just override what was already there.