colour is not getting set to workbook - java

I am using java workbook xls but i am unable to set the color.I am using the following code.
CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
cellStyle.setFillBackgroundColor(HSSFColor.DARK_RED.index);
Cell celli = row0.createCell((short) i);
celli.setCellValue(list.get(i).toString());
celli.setCellStyle(cellStyle);
I am using the cellstyle but color is not being set.

You should use
cellStyle.setFillForegroundColor(HSSFColor.DARK_RED.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
instead of
cellStyle.setFillBackgroundColor(HSSFColor.DARK_RED.index);

Related

How to get cell style by name in Apache poi

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)
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");

Setting RGB Colors with XSSFColor

I'm trying to set an RGB Color Value using XSSFColor setFillForeground() method below
XSSFWorkbook workbook= new XSSFWorkbook();
CellStyle style = workbook.createCellStyle();
Style.cloneStyleFrom(headerStyle);
Style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
XSSFColor color = new XSSFColor(new java.awt.Color(215,228,188)); //accepts a short value
style.setFillForegroundColor(color .getIndexed());
Sheet sheet = workbook.createSheet(sheetName);
Row headerRow = sheet.createRow(0);
Cell cell = headerRow.createCell(i);
cell.setCellStyle(style);
I'm passing the short value however my foreground is getting set to black no matter what the RGB value. I haven't yet discovered why this is - any ideas?
The getIndexed() method in XSSFColor has Javadocs that state that it's for backwards compatibility. Basically, XSSF has no pallette, so it's useless to set an index of color in a CellStyle.
However, XSSF has its own method of setting the foreground color in a style -- using the colors directly. Use the overload of setFillBackgroundColor that directly takes a XSSFColor. It only exists in XSSFCellStyle, not the interface CellStyle, so cast it as a XSSFCellStyle first.
((XSSFCellStyle) style).setFillForegroundColor(color);
You can check the example provided by the Apache Colors and Fills
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell( 0);
cell.setCellValue("custom XSSF colors");
XSSFCellStyle style1 = wb.createCellStyle();
style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128), new DefaultIndexedColorMap()));
style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);

Apache POI style getting applied to all cells

Cell cell = row.createCell(1);
cell.setCellValue(rdf.getEffectiveDate());
cell.getCellStyle().setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy"));
cell = row.createCell(2);
cell.setCellValue(rdf.getExpiryDate());
cell.getCellStyle().setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy"));
row.createCell(3).setCellValue(rdf.getPremium());
row.createCell(4).setCellValue(rdf.getAccountNumber());
row.createCell(5).setCellValue(rdf.getLedgerName());
I wanted to apply Date Format on two of the above columns. But it is getting applied to all the cells. How can I prevent this.
As the documentation states, Cell.getCellStyle() will never return null.
https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#getCellStyle()
When no cell style has been explicitly set for a Cell then it will return the default cell style which is initially shared among all cells in the workbook. Changing this then will obviously affect all cells not having an explictly assigned style.
You need to create a new CellStyle and then assign this to the relevant cells.
From the POI developer guide:
https://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(0);
// Create a cell and put a date value in it. The first cell is not styled
// as a date.
Cell cell = row.createCell(0);
cell.setCellValue(new Date());
// we style the second cell as a date (and time). It is important to
// create a new cell style from the workbook otherwise you can end up
// modifying the built in style and effecting not only this cell but other cells.
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
//you can also set date as java.util.Calendar
cell = row.createCell(2);
cell.setCellValue(Calendar.getInstance());
cell.setCellStyle(cellStyle);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
Try creating a new cell style. I think you may be changing the default style. So something like this...
CellStyle dateTimeCS = wb.createCellStyle();
dateTimeCS.setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy"));
cell.setCellStyle(dateTimeCS);
use RegionUtil to apply borders to a range of cells
https://poi.apache.org/apidocs/org/apache/poi/ss/util/RegionUtil.html
looks like it was added in version 3.15

How to select and bold the whole worksheet with Apache POI

I am a beginner with Apache POI library.
in VBA, I know I can select and bold the whole worksheet with following code
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets(1)
ws.Cells.Font.Bold = True
May I know how to select and bold the whole sheet by coding with Apache POI library?
thanks
There is a pretty good example on this link.
Sheet sheet = wb.createSheet("test");
CellStyle cs = wb.createCellStyle();
Font f = wb.createFont();
f.setBoldweight(Font.BOLDWEIGHT_BOLD);
cs.setFont(f);
sheet.setDefaultColumnStyle(1,cs); //set bold for column 1
The default font for a workbook can be retrieved from index 0. So to modify the font bold setting default for the workbook:
private void setWorkbookDefaultFontToBold(Workbook workbook){
Font defaultFont = workbook.getFontAt(0);
defaultFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
}
It's a really obscure piece of information - it's in the POI Sheet Javadoc for setColumnWidth, in the second or so line:
"...can be displayed in a cell that is formatted with the standard font (first font in the workbook)."
I haven't had to use it heavily, so it may have just happened to work for me (the location and non-prevalence of documentation on it makes me slightly leary of recommending depending on it) but it's somewhere you could start looking
private HSSFFont createAndSetFontStyle(HSSFWorkbook wb) {
HSSFFont font = wb.createFont();
font.setFontName(XSSFFont.DEFAULT_FONT_NAME);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
font.setFontHeightInPoints((short)10);
return font;
}
HSSFCellStyle cellStyle = workBook.createCellStyle();
HSSFFont createfont = createAndSetFontStyle(workBook);
cellStyle.setFont(createfont);
cell.setCellStyle(cellStyle);

How to rotate text in a spreadsheet cell using Apache POI?

How can I rotate the text within an HSSFCell class of Apache POI?
Use HSSFCellStyle, that class has a method called setRotation(short rotation) which will rotate the text. All you do is apply the cell style to a cell:
HSSFCellStyle myStyle = workbook.createCellStyle();
myStyle.setRotation((short)90);
HSSFCell c = row.createCell(columnNumber);
c.setCellStyle(myStyle);
CellStyle cssVertical = wb.createCellStyle();
cssVertical.setFont(f);
cssVertical.setRotation((short)90);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
XSSFRow row = sheet.createRow(1);
XSSFCell cell = row.createCell(1);
XSSFCellStyle cs = workbook.createCellStyle();
cs.setRotation((short) 90); // set text rotation
cs.getStyleXf().setApplyAlignment(true); // <<< Important
cell.setCellValue("Vertical Text");
cell.setCellStyle(cs);
workbook.write(new FileOutputStream("out.xlsx"));
Apache POI 3.17, need to manually add alignment="true" attribute in cellXfs section.

Categories