通过java将数据附加到xlsx文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3177949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:07:13  来源:igfitidea点击:

append data into xlsx file through java

javaapache-poi

提问by Sunil

I am using Apache POI for writing into .xlsxfile. I can write into .xlsxfile but I am unable to append new content. How can I append new content in the .xlsx file?

我正在使用 Apache POI 写入.xlsx文件。我可以写入.xlsx文件,但无法追加新内容。如何在 .xlsx 文件中附加新内容?

My Code is:

我的代码是:

public static void write(){
    try {           
        Workbook[] wbs = new Workbook[]{new XSSFWorkbook()};
        Workbook workbook=wbs[0];
        org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet();
        System.out.println(sheet.getSheetName());
        Row row = sheet.createRow(2);
        for(int i=0;i<10;i++){
               Cell cell=row.createCell(i);
               cell.setCellValue("Sun System");
        }
        FileOutputStream fout=new FileOutputStream("D:/Test.Xlsx");
        workbook.write(fout);
        fout.close();
    } catch (Exception e) {
    }
}

回答by Marc van Kempen

You should open the existing file instead of creating a new one if you want to append, see also this stackoverflow question:

如果要追加,您应该打开现有文件而不是创建新文件,另请参阅此 stackoverflow 问题:

Edit existing excel files using jxl api / Apache POI

使用 jxl api / Apache POI 编辑现有的 excel 文件

回答by Venkat

The first thing U've to do :

你要做的第一件事:

When you're working with Excel 2007 format, its more wise to use XSSF-Implementations, because you've used abstract implementations. Always remember this when using any implementation.

当您使用 Excel 2007 格式时,使用 XSSF 实现更明智,因为您使用了抽象实现。在使用任何实现时始终记住这一点。

To append to an existing file you need to reach the end of the rows in that particular workbook sheet. This can be achieved by:

要附加到现有文件,您需要到达该特定工作簿表中行的末尾。这可以通过以下方式实现:

int rows = sheet.getPhysicalNumberOfRows(); // or sheet.getLastRowNum();

After that you can create new cells with the XSSF- Implementation classes. For more information refer to this page

之后,您可以使用 XSSF-Implementation 类创建新单元格。有关更多信息,请参阅此页面