3

I am using Apache POI for writing into .xlsx file. I can write into .xlsx file but I am unable to append new content. How can I append new content in the .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) {
    }
}
Gagravarr
  • 47,320
  • 10
  • 111
  • 156
Sunil
  • 4,133
  • 6
  • 23
  • 21
  • 1
    What kind of content? Cells? Columns? Worksheets? And about *unable* - because of an error/exception or because you need additional knowledge? – Andreas Dolk Jul 05 '10 at 08:26

3 Answers3

7

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.

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

Jack
  • 2,891
  • 11
  • 48
  • 65
Venkat
  • 2,604
  • 6
  • 26
  • 36
3

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

Edit existing excel files using jxl api / Apache POI

Community
  • 1
  • 1
Marc van Kempen
  • 546
  • 2
  • 7
0

You are creating a new workbook each time this is run youd want to create a FileInputStream with a file path to the excel file and then use that input stream to get the XSSF workbook you want to edit

FileInputStream fis = new FileInputStream(filePath);
XSSFWorkbook workBook = new XSSFWorkbook(fis);

then in order to get a specific sheet you simply just use the .getSheet or getSheetAt methods that are apart of workBook. then create and set cells