Home » excel » excel – JAVA POI unable to understand workbook clonesheet method as I am getting nothing

excel – JAVA POI unable to understand workbook clonesheet method as I am getting nothing

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have only 1 sheet in my workbook and need to create 2 new sheet from the existing one. I am using workbook createsheet method first for creating new sheet and then cloning it with clonesheet method. But while fetching data from sheets I am getting data from only my existing sheet and nothing from newly created sheet. Is something my understanding wrong with clonesheet method. It does not feed data from the existing sheet to new sheet.

XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);\existing sheet
XSSFSheet newSheet = workbook.createSheet("NewSheet");\created new sheet
XSSFSheet newSheet1 = workbook.createSheet("NewSheet2");\created new sheet
newSheet = workbook.cloneSheet(1);\clone sheet from existing sheet
newSheet1 = workbook.cloneSheet(1);\clone sheet from existing sheet

for(int sheetNum=0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
    // while iterating data I am getting records only for existing sheet
    // newSheet and newSheet1 is coming empty.
}

Any help would be appriciated.

Thanks,
Amit

How to&Answers:

Firstly, referring to your code snippet “workbook.sheet(1)” is not exist which is the sheet you want to clone. So, let’s say if you want to clone “workbook.sheet(0)” . Therefore you need to change:

newSheet = workbook.cloneSheet(1);\clone sheet from existing sheet
newSheet1 = workbook.cloneSheet(1);\clone sheet from existing sheet

TO

newSheet = workbook.cloneSheet(0);\clone sheet from existing sheet
newSheet1 = workbook.cloneSheet(0);\clone sheet from existing sheet

if you want to clone the first sheet. If not,make sure you create another sheet and changes the value.

Then, whether

a)save it as new file

FileOutputStream out = new FileOutputStream(new File("<full path where you want to save it>"));) 
workbook.write(out);

or

b)save it to the current file

OR

simply using this code snippet and it automatically create new sheet in the same workbook with the same data with sheet that you clone before.

xSSFSheet newsheet = workbook.cloneSheet(0);

and save it.Good Luck!!! (sorry, if this does not meet your requirement).

Answer:

Another problem with your code even if you get the correct sheet index:

    XSSFSheet newSheet = workbook.createSheet("NewSheet");\created new sheet
    XSSFSheet newSheet1 = workbook.createSheet("NewSheet2");\created new sheet
    newSheet = workbook.cloneSheet(1);\clone sheet from existing sheet
    newSheet1 = workbook.cloneSheet(1);\clone sheet from existing sheet

What you do in the last two lines is actually resetting references of newSheet and newSheet1. After the assignment, they refer to other objects, and the clone won’t be observed in those sheets you create in the first two line.