将数据添加到 excel 中的新单元格而不删除前一个单元格

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

当我尝试向此 xls 文件添加新数据时,我丢失了以前的数据。如何将新信息添加到新单元格并保存?

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

}

您需要输入sheet(使用InputStream),添加记录,然后再次保存。现在您正在创建一个新的工作簿对象,然后使用 OutputStream 写入它,这将覆盖已经存在的内容。

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

希望对您有所帮助