2015-07-11 170 views
10

我正在使用下面的代码来更新excel数据格式,在这里我希望标题以粗体显示,整个数据以斜体显示,但是当我运行代码中的所有功能时似乎工作很好,除了粗体和斜体。代码也可以在没有任何错误的情况下完成执行,但在excel文件中,没有任何单元格使用粗体或斜体格式的数据。粗体和斜体不能在excel中工作EPPLUS

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(); 
     } 
    } 

回答

13

的问题是要设置/设置粗体/斜体后覆盖字体。只需先设定字体是这样的:

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

厄尼感谢您的宝贵答复。 – Ash1994