本文是筆記形式,未作排版git
EPPlus 是一款 .NET 平臺下操做 Excel 的組件,無需依賴 COM 十分方便,相似於 NPOI, 但它只支持操做 Excel,API 比較全並且使用簡單。github
EPPlus 5.x 及以上已經轉換爲商業版,須要購買受權,因此咱們通常能夠安裝 4.x 的最新版來使用。shell
Install-Package EPPlus -Version 4.5.3.3
官方 Wiki https://github.com/JanKallman/EPPlus/wiki 。若遇到使用問題,推薦使用 Google 搜索(搜索關鍵字使用英文),通常都能找到答案。字體
var p = new ExcelPackage(new FileInfo("tmp.xlsx"), new FileInfo(options.TemplateFilePath)); //獲取 Worksheet var ws = p.Workbook.Worksheets[0]; //獲取單元格 var cell = ws.Cells[rowIndex, columnIndex]; //爲單元格設置字體 cell.Style.Font.Color.SetColor(Color.Crimson);
主要是這句 cell.Style.Font.Color.SetColor(Color.Crimson);
,不是直接爲 Color 屬性賦值,而是使用 SetColor()
方法code
單元格批註,在咱們操做 Excel 比較實用的場景:爲單元格值作出錯誤說明,讓用戶知道這個單元格的值爲何錯了,等等。blog
批註的形勢以下:字符串
代碼實現:get
var p = new ExcelPackage(new FileInfo("tmp.xlsx"), new FileInfo(options.TemplateFilePath)); //獲取 Worksheet var ws = p.Workbook.Worksheets[0]; //獲取單元格 var cell = ws.Cells[rowIndex, columnIndex]; var comment = cell.AddComment("錯誤緣由:\r\n", "做者"); comment.Font.Bold = true; var rt = comment.RichText.Add("內容"); rt.Bold = false; comment.AutoFit = true;
注意 AddComment()
方法的第二個參數不能設置爲null或空字符串,否則會報異常。it