Bold and Italics not working in excel with EPPLUS

Ash1994 picture Ash1994 · Jul 12, 2015 · Viewed 17k times · Source

I am using the below code for updating excel data format, here I want the heading to be in bold and entire data in italics format but when I run the code all the features in it seems to be working fine except for Bold and Italics. Code also completes execution without any errors but in the excel file none of the cells are having data in either bold or italics format.

    public void FormatExcel()
    {
        string currentDate = DateTime.Now.ToString("yyyyMMdd");
        FileInfo File = new FileInfo("G:\\Selenium\\Test66.xlsx");
        using (ExcelPackage excel = new ExcelPackage(File))
        {
            ExcelWorksheet worksheet = excel.Workbook.Worksheets[currentDate];
            int totalRows = worksheet.Dimension.End.Row;
            int totalCols = worksheet.Dimension.End.Column;
            var headerCells = worksheet.Cells[1, 1, 1, totalCols];
            var headerFont = headerCells.Style.Font;
            headerFont.Bold = true;
            headerFont.Italic = true;
            headerFont.SetFromFont(new Font("Times New Roman", 12));
            headerFont.Color.SetColor(Color.DarkBlue);
            var headerFill = headerCells.Style.Fill;
            headerFill.PatternType = ExcelFillStyle.Solid;
            headerFill.BackgroundColor.SetColor(Color.Gray);
            var dataCells = worksheet.Cells[2, 1, totalRows, totalCols];
            var dataFont = dataCells.Style.Font;
            dataFont.Italic = true;
            dataFont.SetFromFont(new Font("Times New Roman", 10));
            dataFont.Color.SetColor(Color.DarkBlue);
            var dataFill = dataCells.Style.Fill;
            dataFill.PatternType = ExcelFillStyle.Solid;
            dataFill.BackgroundColor.SetColor(Color.Silver);
            var allCells = worksheet.Cells[1, 1, totalRows, totalCols];
            allCells.AutoFitColumns();
            allCells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            var border = allCells.Style.Border;
            border.Top.Style = border.Left.Style = border.Bottom.Style = border.Right.Style = ExcelBorderStyle.Thin;
            excel.Save();
        }
    }

Answer

Ernie S picture Ernie S · Jul 12, 2015

The problem is you are setting/overwriting the font after you set bold/italic. Just set the font first like this:

headerFont.SetFromFont(new Font("Times New Roman", 12)); //Do this first
headerFont.Bold = true;
headerFont.Italic = true;

or you can even shorten it a bit like this:

headerFont.SetFromFont(new Font("Times New Roman", 12, FontStyle.Italic | FontStyle.Bold));