Reputation: 43
Am using 3.16
I create some cell styles in a method. And I pass on the workbook to another method for setting cell values.
In this scenario, I have to pass all my cell styles as params to other method. Is there a way I pass only workbook and get styles from that workbook itself.
I found
workbook.getCellStyleAt(idx).
But for this, i have to keep indexed track of all styles i created. And hardcode it value. if i code for a new style in between then I may mess up the sheet format as the index numbers will change.
sample code
SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
SXSSFSheet sheet = workbook.createSheet("SheetName");
CellStyle styleBOM = workbook.createCellStyle();
Font fontBOM = workbook.createFont();
fontBOM.setFontHeightInPoints((short) 16);
fontBOM.setFontName("Arial");
fontBOM.setBold(false);
styleBOM.setFont(fontBOM);
CellStyle headKey = workbook.createCellStyle();
Font fontKey = workbook.createFont();
fontKey.setFontHeightInPoints((short) 11);
fontKey.setFontName("Arial");
fontKey.setBold(true);
headKey.setFont(fontKey);
CellStyle headValue = workbook.createCellStyle();
Font fontValue = workbook.createFont();
fontValue.setFontHeightInPoints((short) 11);
fontValue.setFontName("Arial");
fontValue.setBold(false);
headValue.setFont(fontValue);
valueList=someLogicToFetchValues(someInput);
downloadExcel(valueList, workbook,styleBOM, headKey,headValue)
Upvotes: 2
Views: 5809
Reputation: 6038
You could create a static table with all created styles, each identified by its name (or whatever you choose).
Every time you create a style, you add it to that table and when you need it, you read it from that same table.
Something like this:
class CellStyleMap
{
public static synchronized void addStyle(String identifier,
CellStyle style)
{
styles.put(identifier, style);
}
public static synchronized CellStyle getStyle(String identifier)
{
return (styles.get(identifier));
}
private static Hashtable<String, CellStyle> styles = new Hashtable<String, CellStyle>();
} // class CellStyleMap
Within your code:
CellStyle styleBOM = workbook.createCellStyle();
...
CellStyleMap.addStyle("BOM", styleBOM);
And when you need it:
CellStyle styleBOM;
styleBOM = CellStyleMap.getStyle("BOM");
Upvotes: 2