如何使用Java POI更改XLS文件



我做了一个函数,用poi写一个文件.xls:

    public void write() throws IOException{
    String excelFileName = "C:\Users/Default/Desktop/MyFirstExcel.xls";//name of excel file
    String sheetName = "Sheet1";//name of sheet
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet(sheetName) ;
    //iterating r number of rows
    for (int r=0;r <10; r++ )
    {
        HSSFRow row = sheet.createRow(r);
        //iterating c number of columns
        for (int c=0;c < 5; c++ )
        {
            HSSFCell cell = row.createCell(c);
            cell.setCellValue((String)"Cell "+r+" "+c); //+r+" "+c
        }
    }
    FileOutputStream fileOut = new FileOutputStream(excelFileName);
    //write this workbook to an Outputstream.
    wb.write(fileOut);
    fileOut.flush();
    fileOut.close();
            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("Information Dialog");
            alert.setHeaderText(null);
            alert.setContentText("Done");
            alert.showAndWait();                   
}

此方法每次都会创建一个新文件,我想知道如何将信息附加到文件中。我试图把这行写成:

FileOutputStream fileOut = new FileOutputStream(excelFileName,true);

这似乎还不够。

您需要

从文件/输入流创建工作簿对象,然后您可以读取现有的行/单元格/...并修改/添加到内容中,即

InputStream stream = new FileInputStream(excelFileName);
try {
    HSSFWorkbook wb = new HSSFWorkbook(stream);
    ...
    // write to a new file here!
    wb.write(outStream);
} finally {
    stream.close();
}

参见 https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html#HSSFWorkbook(java.io.InputStream(

最新更新