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");
Related
I try to change background color of a row, or highlight it with a different color with use of following code:
FileInputStream fis = new FileInputStream(src);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheetAt(0);
r = sheet.getRow(5);
CellStyle style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.RED.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
r.setRowStyle(style);
FileOutputStream fileOut = new FileOutputStream(excelFileName);
wb.write(fileOut);
wb.close();
fileOut.flush();
fileOut.close();
I create a style, set it to a row and after that I write it out to same file. File is modified when I execute code, but background color isn't changed.
setRowStyle(CellStyle style) doesn't work as you would expect. Taking a look at the XSSFRow source code you will not find an iteration over the cells in the row or something similar.
/**
* Applies a whole-row cell styling to the row.
* If the value is null then the style information is removed,
* causing the cell to used the default workbook style.
*/
#Override
public void setRowStyle(CellStyle style) {
if(style == null) {
if(_row.isSetS()) {
_row.unsetS();
_row.unsetCustomFormat();
}
} else {
StylesTable styleSource = getSheet().getWorkbook().getStylesSource();
XSSFCellStyle xStyle = (XSSFCellStyle)style;
xStyle.verifyBelongsToStylesSource(styleSource);
long idx = styleSource.putStyle(xStyle);
_row.setS(idx);
_row.setCustomFormat(true);
}
}
To my knowledge it is more like setting a default row style. But even when you set a row style this way afterwards created cells in this row won't get this style. Most probably you will have to do the styling cell by cell.
Sorry my English not good.
My code: styledate
CreationHelper createHelper = workbook.getCreationHelper();
styledate.setDataFormat(
createHelper.createDataFormat().getFormat("d-mmm"));
When I create a excel file, the cell set styledate not display "16-Jun". It's "06/16/2018".
If I create input on excel file, it's ok "16-Jun".
I want when I create file, cell will display "16-Jun". Thank for your help.
Whether a cell style will work or not depends on the cell value set into the cell. Your creating of the style looks correct but you do not show how you are setting the cell value into the cell. The style can only work if the cell value is a date value. If it is a string value, then the style cannot work.
The following complete example shows the problem:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreateExcelCustomDateFormat {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
CellStyle styledate = workbook.createCellStyle();
styledate.setDataFormat(createHelper.createDataFormat().getFormat("d-MMM"));
Sheet sheet = workbook.createSheet();
Cell cell;
//This sets date value into cell and does formatting it.
cell = sheet.createRow(0).createCell(0);
cell.setCellValue(java.util.Date.from(java.time.Instant.now()));
cell.setCellStyle(styledate);
String date = "06/17/2018";
//This sets string value into cell. There the format will not work.
cell = sheet.createRow(1).createCell(0);
cell.setCellValue(date);
cell.setCellStyle(styledate);
//This converts string value to date and then sets the date into cell. There the format will work.
cell = sheet.createRow(2).createCell(0);
cell.setCellValue(java.util.Date.from(
java.time.LocalDate.parse(
date,
java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy")
).atStartOfDay(java.time.ZoneId.systemDefault()).toOffsetDateTime().toInstant()
)); //yes, java.time is a monster in usage ;-)
cell.setCellStyle(styledate);
try (FileOutputStream fos = new FileOutputStream("CreateExcelCustomDateFormat.xlsx")) {
workbook.write(fos);
workbook.close();
}
}
}
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);
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);
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);