2015-12-24 66 views
3

當我嘗試向此xls文件添加新數據時,我丟失了以前的數據。如何將新信息添加到新單元格並保存?將數據添加到excel中的新單元而不刪除以前的單元格

我的代碼就是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) { 

} 
+0

查看我們的這個問題,它具有很好的答案[鏈接](http://stackoverflow.com/questions/521274/edit-現有的excel文件使用jxl-api-apache-poi) –

+0

使用save()保存數據 –

回答

4

您需要輸入表(使用的InputStream),添加記錄,然後再保存。現在你正在創建一個新的工作簿對象,然後用OutputStream編寫它,它將覆蓋已經存在的內容。

2

ORIGINAL

的教程here是非常有益的,寫得很好。他們使用由Apache POI項目開發的外部JAR。 下面是編輯一個單元的一個簡單的例子:

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(); 

希望它可以幫助

相關問題