我创建了一个扩展方法来帮助减少代码量:
public static class RichtTextExtensions
{
public static ExcelRichText Add(this ExcelRichTextCollection richTextCollection,
string text, bool bold = false, bool italic = false, Color? color = null, float size = 11,
bool underline = false, string fontName = "Segoe UI Light")
{
var richText = richTextCollection.Add(text);
richText.Color = color ?? Color.Black;
richText.Bold = bold;
richText.Italic = italic;
richText.Size = size;
richText.FontName = fontName;
richText.UnderLine = underline;
return richText;
}
}
使用方法如下:
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
using (ExcelRange cellRange = worksheet.Cells[1,1])
{
cellRange.RichText.Add("This is ", size: 18, underline:true);
cellRange.RichText.Add("a simple ", bold: true, size: 18, underline: true);
cellRange.RichText.Add("test ", size: 18, underline: true);
cellRange.RichText.Add("of the extension method", bold: true, size: 18, underline: true);
}
不确定为什么EPPlus没有类似此功能,或者他们可能已经有了,而我错过了。