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"));
Related
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.
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);
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)
I need to apply specific data format to cell.
XSSFCellStyle cellStyle = workBook.createCellStyle();
XSSFDataFormat format = workBook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("m/d/yy h:mm"));
dataCell.setCellType(1); //String
dataCell.setCellStyle(cellStyle);
The data is being written but the problem is that the format is applied only when I open excel sheet (in Excel application), click inside the cell with my data.
And then pressing Enter key.
Only then the format is applied.
How can I apply the format without clicking on every cell?
Your problem is that you're setting the cell to be a string. For the most part, cell formatting rules only apply to numeric cells. They don't apply to string cells, those don't get formatted (as they're already formatted to a string!)
XSSFCellStyle cellStyle = workBook.createCellStyle();
XSSFDataFormat format = workBook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("m/d/yy h:mm"));
dataCell.setCellStyle(cellStyle);
// Set Cell Type not really needed, the setCellValue does it
dataCell.setCellType(Cell.CELL_TYPE_NUMERIC);
// Set a date value (2012-06-05 08:50)
dataCell.setCellValue(new Date(1338878999635));
When you open that in Excel, it ought to be have as expected
This is how you change the cell format to Date.
var workBook = new XSSFWorkbook();
var sheet = workBook.CreateSheet("Sheet1");
var dateStyle = workBook.CreateCellStyle();
var dataFormat = workBook.CreateDataFormat();
dateStyle.DataFormat = dataFormat.GetFormat("M/D/YYYY");
row.CreateCell(0).SetCellValue(item.ModifiedDate.HasValue ?
item.ModifiedDate.Value.ToShortDateString(): "");
row.Cells[0].CellStyle = dateStyle; // This will change your cell to date
format.
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.