Apache POI - issue with cell background color - java

I want to color an Excel cell with blue color :
HSSFCellStyle headerCellStyle = worksheet.getWorkbook().createCellStyle();
headerCellStyle.setFillBackgroundColor(HSSFColor.BLUE.index);
headerCellStyle.setFillPattern(CellStyle.FINE_DOTS);
cell = rowHeader.createCell(startColIndex++);
cell.setCellValue("Titre");
cell.setCellStyle(headerCellStyle);
The cell should be blue instead of grey. I don't understant what I am doing wrong.

Related

How to set multiple cell styles to one cell apache POI [duplicate]

I want to apply colour to cell as well as Format Cell value(e.g. Date,Amount).But when I am applying two Cell Style only the last style is gets applied on cell.
//before this colourCellStyle and dateCellStyle are the formatting style
cell9 = row.createCell(9);
cell9.setCellValue(getLoadDate());
cell9.setCellStyle(colourCellStyle);
cell9.setCellStyle(dateCellStyle);
Multiple cell styles cannot be applied to a single Cell. The last cell style applied will overwrite any pre-existing cell style on the Cell. Setting multiple CellStyles won't combined the set attributes of each style.
The solution is to create another CellStyle that has the desired attributes of both of the other CellStyles. You can use the cloneStyleFrom method to start with the attributes of one CellStyle.
CellStyle combined = workbook.createCellStyle();
combined.cloneStyleFrom(colourCellStyle);
combined.setDataFormat(dateCellStyle.getDataFormat());
// You can copy other attributes to "combined" here if desired.
cell9.setCellStyle(combined);
This technique can be generalized to clone any existing cell style and copy individual attributes from a second existing cell style. As always, reuse any existing CellStyles, but if a different combination of attributes is required, then you must create and use a new CellStyle.
You can create a map of styles and then you can use different styles throughout the java program.
For example
Map<String, CellStyle> cellStyles = new HashMap<String, CellStyle>();
DataFormat dataFormat = workbook.createDataFormat();
XSSFCellStyle cellStyle;
XSSFFont font;
cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
cellStyle.setAlignment(cellStyle.ALIGN_CENTER_SELECTION);
font = workbook.createFont();
font.setFontHeightInPoints((short)16);
font.setFontName("Calibri");
cellStyle.setFont(font);
cellStyles.put("header_cell_style", cellStyle);
cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(cellStyle.ALIGN_CENTER_SELECTION);
font = workbook.createFont();
font.setFontHeightInPoints((short)12);
font.setFontName("Calibri");
cellStyle.setFont(font);
cellStyles.put("normal_cell_style", cellStyle);
cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(cellStyle.ALIGN_CENTER_SELECTION);
cellStyle.setDataFormat(dataFormat.getFormat("dd-mmm-yyyy"));
font = workbook.createFont();
font.setFontHeightInPoints((short)12);
font.setFontName("Calibri");
cellStyle.setFont(font);
cellStyles.put("date_cell_style", cellStyle);
cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(cellStyle.ALIGN_CENTER_SELECTION);
cellStyle.setDataFormat(dataFormat.getFormat("dd-mmm-yyyy"));
font = workbook.createFont();
font.setFontHeightInPoints((short)16);
font.setFontName("Calibri");
cellStyle.setFont(font);
cellStyles.put("header_date_cell_style", cellStyle);
return cellStyles;
and then use this map like
Map<String, CellStyle> multipleCellStyles = createMultipleExcelCellStyles(workbook);
headerCellD1.setCellStyle(multipleCellStyles.get("header_cell_style"));
cellB.setCellStyle(multipleCellStyles.get("normal_cell_style"));
cellC.setCellStyle(multipleCellStyles.get("date_cell_style"));

Excel Sheet with existing Date style not working

Need to fill data in Excel template , whcih has Date format style applied to cells. Somehow Date format is not reflecting after filling data in excel cell.
if (cellVal instanceof Date || cellVal instanceof Timestamp) {
cell.setCellValue("20-08-2019"));
CellStyle style = cell.getCellStyle();
cell.setCellStyle(style);
}
Here cell.getCellStyle() to get existing cell style from excel template which should convert date in this format: "20-AUG-19"
issue is even after appying this style cell.setCellStyle(style), Date values style remained same i.e. "20-08-2019"
CellStyle style = cell.getCellStyle();
cell.setCellStyle(style);
you are getting the style of cell variable and setting it again to cell so you're not changing anything at all.
your code should be like that:
CellStyle style = cellVal.getCellStyle(); //cellVal instead of cell
cell.setCellStyle(style);

SXSSF can't create Font and DateFormat

Question
In a SXSSF Workbook:
How can I set font?
How can I set celltype to date?
Context
I need to write an excel .xlsx file with a huge amount of rows and columns (400.000 rows, 50 fields each) so I'm using apache poi, SXSSF workbook. I created a test file with this amount of dummy text and it works but I want cells to have a custom font: so if text is somehow representing time cell type should be set to "date" (allowing me to filter rows by date easily).
I wrote a function which allows me to create a cell, check and modify its text type (currency, string, data) based on textType value that I pass to the function. Text type is correctly recognized as I examine data. Currency and text are correctly modified but when I tried to set Font and Data type it doesn't work at all.
(I already have a working function (XSSF) which creates an excel with custom font and different data types included "date", it just can't generate large excel files due to GC overhead, that's why I had to switch to SXSSF)
Error
I get this kind of compile error.
Errors incompatible types;found :
org.apache.poi.ss.usermodel.Font,required:
org.apache.poi.xssf.usermodel.XSSFFont at line 235 (235:40)
incompatible types;found :
org.apache.poi.ss.usermodel.DataFormat,required:
org.apache.poi.xssf.usermodel.XSSFDataFormat at line 271 (271:54)
incompatible types;found :
org.apache.poi.ss.usermodel.DataFormat,required:
org.apache.poi.xssf.usermodel.XSSFDataFormat at line 308 (308:54)
incompatible types;found :
org.apache.poi.ss.usermodel.DataFormat,required:
org.apache.poi.xssf.usermodel.XSSFDataFormat at line 335 (335:54)
incompatible types;found :
org.apache.poi.ss.usermodel.DataFormat,required:
org.apache.poi.xssf.usermodel.XSSFDataFormat at line 375 (375:66)
Since SXSSFFont doesn't exists, I tried to fix it by creating a Font object and then using it instead of XSSFFont.
Same for DataFormat.
But I still find types issues here and there in code.
XSSFFont font = (XSSFFont) workbook.createFont();
XSSFDataFormat df = (XSSFFont) workbook.createDataFormat();
Also tried code above but it doesnt work, I get
ClassCastException error
Code
//[...]
SXSSFWorkbook workbook = new SXSSFWorkbook(100);
Sheet sheet;
Row row;
Cell cell;
//[...]
XSSFFont font = workbook.createFont();
font.setBold(fontBold);
font.setItalic(fontItalic);
font.setFontHeightInPoints( (short) fontSize);
if (!fontUnderline) {
font.setUnderline(FontUnderline.NONE);
}
else {
font.setUnderline(FontUnderline.SINGLE);
}
font.setColor(fontColor);
CellStyle style = workbook.createCellStyle();
style.setFont(font);
//[...]
if (textType == 'T') {
XSSFDataFormat df = workbook.createDataFormat();
style.setDataFormat(df.getFormat("d-mmm-yyyy hh:mi:ss"));
Calendar c = Calendar.getInstance();
c.set(year, month, day, hour, minute,second);
cell.setCellValue(c.getTime());
}
//in the end I set cell value and style
cell.setCellStyle(style);
cell.setCellValue(text);
Here I created a short example using a SXSSFWorkbook and filling 1 cell with a date and applying the proper format as well as a font.
SXSSFWorkbook s = new SXSSFWorkbook();
Font font = s.createFont();
font.setBold(true);
font.setItalic(true);
short dateStyle = s.createDataFormat().getFormat("mm/dd/yy;#");
CellStyle dateCellFormat = s.createCellStyle();
dateCellFormat.setDataFormat(dateStyle);
dateCellFormat.setFont(font);
SXSSFSheet sheet = s.createSheet("Test");
Row r = sheet.createRow(0);
Cell c = r.createCell(0);
c.setCellValue(new Date());
c.setCellStyle(dateCellFormat);
s.write(Files.newOutputStream(Paths.get("D:/test.xlsx"), StandardOpenOption.CREATE_NEW));
s.close();
You will have to make some adjustments, but I hope you get the idea (use the appropriate Interface's)

Getting Excel cell background color using POI in Java doesn´t match

I am converting an Excel table to HTML.
I am using POI in Java to get the color of the cell in an xls workbook.
The problem is that the colors don´t match: In Excel I have RGB values of 242, 220, and 219, but when I get them using POI I get RGB(255,153,204).
Any idea on how to get the exact color?
HSSFCellStyle cs = (HSSFCellStyle) style;
out.format(" /* fill pattern = %d */%n", cs.getFillPattern());
styleColorback(out, "background-color", cs.getFillForegroundColorColor())
private void styleColorback(Formatter out, String attr, HSSFColor color) {
short[] rgb = color.getTriplet();
out.format(" %s: #%02x%02x%02x; ", attr, rgb[0], rgb[1], rgb[2]);
}
I think that it isn´t possible to obtain the exact color of the cell because of Excel 2003 palette contains only 56 colors.
The unique way that I found to get the exact color is that when you save the Excel format as .xls in the options of excel and then in save menu there we can change the colors of the palette for the desired color.

Why does org.apache.poi.hssf give wrong color with Excel 2007?

Why does org.apache.poi.hssf give the wrong color a cell which with Excel 2007? With the 2010 version there are no problem.
Any idea for a fix/workaround?
final HSSFCellStyle cellStyle = (HSSFCellStyle) cell.getCellStyle();
final HSSFColor backgroundColor = cellStyle.getFillForegroundColorColor();
String theColor = ExcelToHtmlUtils.getColor( backgroundColor );
I tried couple libraries but no luck. Only xlsgen gives good results but it is not open source, which I would prefer.
One thing that I notice: you seem to want the background color, but you instead ask for the FillForegroundColorColor. I think you want to do this instead:
final HSSFColor backgroundColor = cellStyle.getFillBackgroundColorColor();
Try that instead and let us know.

Categories

Resources