Jenny
Jenny

Reputation: 545

appending to an existing excel file using XSSFWorkbook

I am trying to write a code that will append data to already existing excel spreadsheet. However when I run this code the file becomes corrupted.

In case of this code I am trying to add a spreadsheet, but i have tryed with cells in existing sheet to no luch and all the same error. Am I missing something, looks like i am creating an Excel adding some data then writing, closing it. and then just adding a new sheet to an existing workbook and writing it again to the stream.

public class PlayWithExcel {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    Workbook wb = new XSSFWorkbook();
    XSSFSheet ws = (XSSFSheet) wb.createSheet("Initial Data");
    XSSFSheet ws1 = (XSSFSheet) wb.createSheet("Cross Referenced");
    XSSFSheet ws2 = (XSSFSheet) wb.createSheet("HPD");

    Row row = ws.createRow(0);
    row.createCell(0).setCellValue("Value");
    row = ws1.createRow(2);
    row.createCell(3).setCellValue("Address");

    try {
        String path = "C:/Users/Jenny/Desktop/Test.xlsx";
        FileOutputStream out = new FileOutputStream(path);
        wb.write(out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }


    XSSFSheet ws3 = (XSSFSheet) wb.createSheet("another sheet");


    try {
        String path = "C:/Users/Jenny/Desktop/Test.xlsx";
        FileOutputStream out = new FileOutputStream(path);
        wb.write(out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Upvotes: 4

Views: 12140

Answers (1)

Sankumarsingh
Sankumarsingh

Reputation: 10079

Many people facing the issue when trying to write more than once. This is a known issue in POI.

However I'll suggest you try to reload the file using fileinputstream when you write very first time and you need to reload access the file again.

try {
    String path = "C:/Users/Jenny/Desktop/Test.xlsx";
    FileOutputStream out = new FileOutputStream(path);
    wb.write(out);
    out.close();
    wb = new XSSFWorkbook(new FileInputStream(path));
} catch (Exception e) {
    e.printStackTrace();
}

Upvotes: 4

Related Questions