粗体和斜体不工作在excel与EPPLUS
本文关键字:excel EPPLUS 工作 斜体 | 更新日期: 2023-09-27 18:02:11
我使用下面的代码来更新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();
}
}
问题是您在设置粗体/斜体后设置/覆盖字体。先设置字体,像这样:
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));
headerFont.SetFromFont("Times New Roman", 16, true);