Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache POI difference between cloning style and getting style

Are there any significant differences between doing:

CellStyle newCellStyle = workbook.createCellStyle();
neweCellStyle.cloneStyleFrom(oldCell.getCellStyle());
newCell.setCellStyle(newCellStyle);

versus

CellStyle newCellStyle = oldCell.getCellStyle();
newCell.setCellStyle(newCellStyle);

the reason why I ask this is because I'm not sure if by taking the first approach I risk creating too many CellStyles, I've encountered issues where if I create too many CellStyles in one particular workbook, all styling for the workbook disappear. So is there anything wrong with taking the second approach?

like image 959
Stupid.Fat.Cat Avatar asked Jun 11 '14 14:06

Stupid.Fat.Cat


2 Answers

The first approach will create a new cell style for every new cell, which as you've rightly noticed might lead to the situation where you end up to the 'CellStyle explosion'.

The potential benefit (or drawback - depending on your use case) of this solution is the situation where every cell references a different cell style object, so changes to the style of one cell won't impact any other cell (might be useful if you want to amend the style for only selected part of your spreadsheet in the future).

In the second approach, all cells referencing the same style would be modified, though there is a neat way around this (when necessary) by using CellUtil which you can find covered in more details in another Stack Overflow post here.

like image 97
Norbert Radyk Avatar answered Nov 05 '22 21:11

Norbert Radyk


There is another difference if you are trying to copy the cell style from the same workbook or not. The second approach will generate an error if you are copying from a different workbook:

java.lang.IllegalArgumentException: This Style does not belong to the supplied Workbook Stlyes Source. Are you trying to assign a style from one workbook to the cell of a differnt workbook?

In case of distinct file you need to use the first approach.

like image 42
Aldo Inácio da Silva Avatar answered Nov 05 '22 21:11

Aldo Inácio da Silva