tags:

views:

149

answers:

2
+3  A: 

How can I copy a worksheet in one workbook to a new worksheet in another workbook?

This can be done, but requires a little work. Firstly, you have to copy it cell (within a couple of nested for loops). For each cell you need to invoke the copyTo() method, which will produce a deep copy. However the format is only shallow copied, so you will need to get the cell format and use the copy constructor of that, and then call setCellFormat on the cell you have just copied. Then add the duplicate cell to the new spreadsheet

The code might look as follows:

for (int i = 0 ; i < numrows ; i++){
   for (int j = 0 ; j < numcols ; j++){
       readCell = sheet.getCell(i, j);
       newCell = readCell.copyTo(i, j);
       readFormat = readCell.getCellFormat();
       newFormat = new WritableCellFormat(readFormat);
       newCell.setCellFormat(newFormat);
       newSheet.add(newCell);
   }

}


Resources :

Colin Hebert
To use the copyTo method the cell must be a WritableCell. So how could I make a Cell to a WritableCell?
János Harsányi
@János Harsányi, for this you'll need a `WritableSheet`, the `getWritableCell()` will return a `WritableCell`, and for that you'll need a `WritableWorkbook`
Colin Hebert
I see. But how could I *open* an excel document as a `WritableWorkbook`? And is it possible to copy from one file to an other?
János Harsányi
@János Harsányi, you can't simply open a `WritableWorkbook` you have to open a `Workbook` with `getWorkbook()` and create a `WritableWorkbook` in a temp file with `createWorkbook()` (and your opened workbook in parameter).
Colin Hebert
@János Harsányi, after your edit, you'll need to check that `readFormat` isn't `null`
Colin Hebert
Now it's working, unfortunately it won't copy charts and conditional formatting (?). Is there any way to copy them too?
János Harsányi
@János Harsányi, I think those features are too much to handle for this lib (or any XLS lib that I know of).
Colin Hebert
+1  A: 

You have to loop through the cells one by one and add them to the new sheet.

See this, under question How can I copy a worksheet in one workbook to a new worksheet in another workbook?

Nivas