Excel中使用EPPLUS时加粗和斜体无效

16

我正在使用以下代码更新Excel数据格式,在这里我希望标题为粗体,整个数据为斜体格式,但当我运行代码时,它似乎所有功能都能正常工作,除了粗体和斜体。代码也在没有任何错误的情况下完成执行,但在Excel文件中,没有任何单元格具有粗体或斜体格式的数据。

    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();
        }
    }
2个回答

22

问题是您在设置/覆盖粗体或斜体后才设置字体。请先像这样设置字体:

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

或者你甚至可以将其缩短,像这样:

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

0

headerFont.SetFromFont("Times New Roman", 16, true);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接