Add data to xlsx file via java

I am using Apache POI to write to a file .xlsx. I can write to a file .xlsx, but I cannot add new content. How to add new content to a .xlsx file?

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) {
    }
}
+3
source share
2 answers

The first thing to do:

When you work with the Excel 2007 format, it is more reasonable to use XSSF implementations because you used abstract implementations. Always keep this in mind when using any implementation.

To add to an existing file, you need to go to the end of the lines in this sheet of the book. This can be achieved:

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

XSSF-. .

+6

Source: https://habr.com/ru/post/1753123/


All Articles