3

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) {

}
Hussein El Feky
  • 6,627
  • 5
  • 44
  • 57
omar karsly
  • 33
  • 1
  • 6

2 Answers2

4

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.

cbender
  • 2,231
  • 1
  • 14
  • 18
2

ORIGINAL

The tutorials here are very helpful and well-written. They use an external JAR developed by the Apache POI project. Here's an simple example of editing one cell:

    InputStream inp = new FileInputStream("wb.xls");
    Workbook wb = WorkbookFactory.create(inp);
    Sheet sheet = wb.getSheetAt([sheet index]);
    Row row = sheet.getRow([row index]);
    Cell cell = row.getCell([cell index]);
    String cellContents = cell.getStringCellValue(); 
    //Modify the cellContents here
    // Write the output to a file
    cell.setCellValue(cellContents); 
    FileOutputStream fileOut = new FileOutputStream("wb.xls");
    wb.write(fileOut);
    fileOut.close();

Hope it helps

Community
  • 1
  • 1
Eric G
  • 928
  • 1
  • 9
  • 29