How to select and bold the whole worksheet with Apache POI - java

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

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

colour is not getting set to workbook

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

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 link a image from excel file using POI

I am writting some text say "Pass" into excel file using cell.setCellValue("Pass"). Now I have to create a link to an image which locates at directory (C:\Users\UserName\DeskTop\image\test.jpg) from an excel.
When I click on text pass from excel file, then it should open the test.jpg image.
Please guide me/share to JAVA code to achieve this.
Thanks,
Md Ashfaq
Ashfaq...Following is a method you can user for hyperlink the screenshot with the cell.
public static void hyperlinkScreenshot(XSSFCell cell, String FileAddress){
XSSFWorkbook wb=cell.getRow().getSheet().getWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
CellStyle hlink_style = wb.createCellStyle();
Font hlink_font = wb.createFont();
hlink_font.setUnderline(Font.U_SINGLE);
hlink_font.setColor(IndexedColors.BLUE.getIndex());
hlink_style.setFont(hlink_font);
Hyperlink hp = createHelper.createHyperlink(Hyperlink.LINK_FILE);
FileAddress=FileAddress.replace("\\", "/");
hp.setAddress(FileAddress);
cell.setHyperlink(hp);
cell.setCellStyle(hlink_style);
}
for details check here.
Cell.Hyperlinks.Add Anchor:=Selection, Address:= _
"C:\Users\UserName\DeskTop\image\test.jpg", TextToDisplay:="pass"
You can remove the setvalue as TextToDisplay can handle this...

Categories