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

}
2
  • Check our this question, it has good answers link
    – Eric G
    Commented Dec 24, 2015 at 17:34
  • use save() to save data Commented Dec 24, 2015 at 17:34

2 Answers 2

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.

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.