Java code for excel row in Bold text style with Background color

apache-poi, excel, java

Solution

You are doing wrong in the following:

1- You are not setting any Background color;

2- When you create the new cells they override the row style, so you need to set the style for each new cell you create;

Below is the working code:

FileOutputStream fileOut = new FileOutputStream("poi-test.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Readings");
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontHeightInPoints((short)11);
font.setFontName(HSSFFont.FONT_ARIAL);
font.setBoldweight(HSSFFont.COLOR_NORMAL);
font.setBold(true);
font.setColor(HSSFColor.DARK_BLUE.index);

style.setFont(font);
//Add these lines     
style.setFillForegroundColor(IndexedColors.AQUA.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);

sheet.createFreezePane(0, 1); // Freeze 1st Row   sheet.createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow)


 HSSFRow rowhead = sheet.createRow((short) 0);
 rowhead.setRowStyle(style);
 //Set the cell0 Style        
 HSSFCell cell0 = rowhead.createCell(0);
 cell0.setCellStyle(style);
 cell0.setCellValue("ROW");
 //Set the cell1 Style        
 HSSFCell cell1 = rowhead.createCell(1);
 cell1.setCellStyle(style);
 cell1.setCellValue("NUMBER");

 workbook.write(fileOut);

file output:

Problem

I have googled some code and found some answers but not able to get my excel file output in Bold and set background color. I have tried with following code. can you please tell me where am I going wrong? Please take a look. Thanks. FYI: I am going to make 1st Row in BOLD with blue or any Light color background. If you know please help with the code. ``` // Excel file generation code HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Readings"); CellStyle style = workbook.createCellStyle(); Font font = workbook.createFont(); font.setFontHeightInPoints((short)11); font.setFontName(HSSFFont.FONT_ARIAL); font.setBoldweight(HSSFFont.COLOR_NORMAL); font.setBold(true); font.setColor(HSSFColor.DARK_BLUE.index); style.setFont(font); // Freeze 1st Row sheet.createFreezePane(0, 1); HSSFRow row = sheet.createRow(1); HSSFRow rowhead = sheet.createRow((short) 0); rowhead.setRowStyle(style); rowhead.createCell(0).setCellValue("RUN"); rowhead.createCell(1).setCellValue("NUMBER"); ```

Original source