63

How to make an entire excel row cells bold text using Apache POI?

E.g:
Column headings should be in bold. Instead of applying style for each and every cell of heading row, how can I apply some style to an entire row?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Krishnamachary
  • 631
  • 1
  • 5
  • 4
  • this is also helpful: http://thinktibits.blogspot.com/2012/12/Java-POI-Format-Excel-Cell-Bold-Example-Program.html – NoNaMe Feb 27 '15 at 10:03
  • This link might help you. [http://stackoverflow.com/questions/37188540/java-code-for-excel-row-in-bold-text-style-with-background-color](http://stackoverflow.com/questions/37188540/java-code-for-excel-row-in-bold-text-style-with-background-color) – Peter May 13 '16 at 05:35

6 Answers6

57

This should work fine.

    Workbook wb = new XSSFWorkbook("myWorkbook.xlsx");
    Row row=sheet.getRow(0);
    CellStyle style=null;

    XSSFFont defaultFont= wb.createFont();
    defaultFont.setFontHeightInPoints((short)10);
    defaultFont.setFontName("Arial");
    defaultFont.setColor(IndexedColors.BLACK.getIndex());
    defaultFont.setBold(false);
    defaultFont.setItalic(false);

    XSSFFont font= wb.createFont();
    font.setFontHeightInPoints((short)10);
    font.setFontName("Arial");
    font.setColor(IndexedColors.WHITE.getIndex());
    font.setBold(true);
    font.setItalic(false);

    style=row.getRowStyle();
    style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFont(font);

If you do not create defaultFont all your workbook will be using the other one as default.

halfer
  • 19,824
  • 17
  • 99
  • 186
ArtiBucco
  • 2,199
  • 1
  • 20
  • 26
  • Sorry, I forgot to mentntion. I am using HSSFWorkbook. – Krishnamachary Sep 08 '12 at 18:21
  • 4
    HSSFWorkbook hwb=new HSSFWorkbook(); HSSFSheet sheet=hwb.crateSheet("New Sheet"); HssfRow headRow=sheet.createRow((int)0); CellStyle style=headRow.getRowStyle(); Font boldFont=hwb.createFont(); boldFont.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setFont(boldFont); //headRow.setRowStyle(style);--> this is not working Cell cell=headRow.createCell((int)0) cell.setCellStyle(style);--> this is working I want to apply the bold style to entite row, instead of individual cells. – Krishnamachary Sep 08 '12 at 18:47
  • 31
    `row.getRowStyle()`returns null for me – Danny Lo Nov 01 '14 at 18:19
  • 5
    even if the columns are created still row.getRowStyle() returns null – LittleBit May 07 '16 at 08:20
  • 1
    https://stackoverflow.com/questions/25437431/make-the-entire-row-bold-using-apache-poi – Alfaz Jikani Oct 11 '17 at 13:27
  • It looks like `sheet` here hasn't been set yet, either. I think there should be a `workbook.createSheet("Sheet Name");` call here. – ebwb Aug 28 '18 at 15:50
22

Please find below the easy way :

XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop((short) 6); // double lines border
style.setBorderBottom((short) 1); // single line border
XSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 15);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);                 

Row row = sheet.createRow(0);   
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
cell0.setCellStyle(style);  
for(int j = 0; j<=3; j++)
row.getCell(j).setCellStyle(style);
Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
satender
  • 1,199
  • 13
  • 12
13

This work for me

I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilà first row is bolded.

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0); 
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);
Adhamo
  • 131
  • 1
  • 5
6

This worked for me

    Object[][] bookData = { { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 },
            { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 } };

    String[] headers = new String[] { "HEader 1", "HEader 2", "HEader 3" };

    int noOfColumns = headers.length;
    int rowCount = 0;

    Row rowZero = sheet.createRow(rowCount++);
    CellStyle style = workbook.createCellStyle();
    Font font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style.setFont(font);
    for (int col = 1; col <= noOfColumns; col++) {
        Cell cell = rowZero.createCell(col);
        cell.setCellValue(headers[col - 1]);
        cell.setCellStyle(style);
    }
omkar sirra
  • 696
  • 10
  • 28
  • 1
    Do you by any chance know why row.setRowStyle() is not working? :/ – Erdal G. Jul 29 '16 at 17:59
  • No Erdal. If it worked, I would have done row by row only Instead of column by column overhead. – omkar sirra Jul 31 '16 at 13:32
  • 1
    @ErdalG. row.setRowStyle works if set after setting values in the cells of the row. If in above answer, setRowStyle is done after for loop, it will work! Tested with Poi 3.9 version. – Champ Dec 08 '17 at 20:24
  • @ErdalG.Sorry. I am only partially correct. It works with LibreOffice but not MS Excel! May want to check with latest excel though. – Champ Dec 11 '17 at 19:43
0

A worked, completed and simple example:

package io.github.baijifeilong.excel;

import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

/**
 * Created by BaiJiFeiLong@gmail.com at 2019/12/6 11:41
 */
public class ExcelBoldTextDemo {

    @SneakyThrows
    public static void main(String[] args) {

        new XSSFWorkbook() {{
            XSSFRow row = createSheet().createRow(0);
            row.setRowStyle(createCellStyle());
            row.getRowStyle().getFont().setBold(true);
            row.createCell(0).setCellValue("Alpha");
            row.createCell(1).setCellValue("Beta");
            row.createCell(2).setCellValue("Gamma");
        }}.write(new FileOutputStream("demo.xlsx"));
    }
}
BaiJiFeiLong
  • 3,716
  • 1
  • 30
  • 28
0
public class ExcelReader {

    private XSSFWorkbook workBook;
    private XSSFSheet workSheet;


    public ExcelReader(String path, String sheetName){
        File file = new File(path);
        try {
            FileInputStream inputStream = new FileInputStream(file);
            workBook = new XSSFWorkbook(inputStream);
            workSheet = workBook.getSheet(sheetName);
            workBook.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public Object[][] getData(){

        int rows = workSheet.getLastRowNum(); // returns number of rows
        int cols = workSheet.getRow(0).getLastCellNum(); //returns number of cols

        Object[][] data = new Object[rows][1];

        for (int i = 0; i < rows; i++) {
            Map<String,String> map = new HashMap<>();

            for (int j = 0; j < cols; j++) {
                //each column name is a key
                XSSFCell cell = workSheet.getRow(i + 1).getCell(j);// might be null sometimes if the cell is empty

                if (cell == null){
                    System.out.println();
                }

                map.put(workSheet.getRow(0).getCell(j).toString(),
                        // each cell under column name will be value
                        cell == null  ? "" : cell.toString() );
            }
            data[i][0] = map;
        }
        return data;
    }

}
Laurel
  • 5,965
  • 14
  • 31
  • 57
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 03 '22 at 04:52