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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With