mememoremore
mememoremore

Reputation: 292

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

Upvotes: 10

Views: 19420

Answers (3)

romeara
romeara

Reputation: 1516

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

Upvotes: 10

swamy
swamy

Reputation: 1210

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

Upvotes: 1

CoolBeans
CoolBeans

Reputation: 20820

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

Upvotes: 15

Related Questions