Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new sheets to existing excel workbook using apache POI?

I am trying to write List data into multiple excel sheet in one work book. like for first list, the code will create new workbook and create new sheet for list[1], for second list it will create new sheet in existing workbook and so on. so i wrote below code. but it doesnt work and i am able to see only first sheet for list[1]. can someone help me to provide any alternate resolutions?

the below code i have written

    ArrayList<List<String>> tempresultdata=this.getSummaryList();
    HSSFWorkbook workbook = new HSSFWorkbook();
    String fileName="Path\\To\\XLS";
    File file = new File(fileName);
    FileOutputStream out;           
    if(!file.exists()) // This will create new workbook with new sheet if it doesnt exists{

                HSSFSheet mySheet = workbook.createSheet(sheetname);
                writeExcel(mySheet,tempresultdata);
    } else // This add new sheet to above created workbook {
            try {
                HSSFWorkbook myWorkBook = (HSSFWorkbook) WorkbookFactory.create(file);
                workbook=myWorkBook;
                HSSFSheet mySheet = (HSSFSheet) workbook.createSheet(sheetname);
                writeExcel(mySheet,tempresultdata);                 
            } catch (InvalidFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }   
    try{
        out = new FileOutputStream(fileName,true);
        workbook.write(out);
        out.close();
        }catch(Exception e){ 
            e.printStackTrace();
        }

Thanks, Priyank Shah

like image 889
Priyank Shah Avatar asked Sep 17 '12 12:09

Priyank Shah


2 Answers

If file does not exist then this code creates new file and also creates sample sheet1 but if file exists then it adds new sheet to existing excel file.

    HSSFWorkbook workbook = null;
    File file = new File(context.getExternalFilesDir(null), "Sample.xls");
    FileOutputStream fileOut = new FileOutputStream(file);

    if (file.exists()) {
        try {
            workbook = (HSSFWorkbook)WorkbookFactory.create(file);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }
        HSSFSheet sheet = workbook.createSheet("Sample sheet2");
    }
    else{
        workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Sample sheet1");
    }
    workbook.write(fileOut);
    fileOut.close();
like image 97
Bhaskar Avatar answered Oct 23 '22 13:10

Bhaskar


Looks like you are only writing out the sheet not the workbook

like image 30
John B Avatar answered Oct 23 '22 12:10

John B