如何检索细胞的颜色?

时间:2016-01-12 20:49:40

标签: c# xlsx epplus

我想用epplus获取单元格颜色。在Excel单元格中,我有彩色文本。此代码不返回单元格颜色。我不明白为什么。我希望获得单元格的所有颜色,然后将其添加到带有文本的Dictionary

FileInfo file = new FileInfo("K:\\1.xlsx");
var package = new ExcelPackage(file);

ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
var start = worksheet.Dimension.Start;
var end = worksheet.Dimension.End;
    for (int row = start.Row; row <= end.Row; row++)
        { 
              for (int col = start.Column; col <= end.Column; col++)
              { 
                 var color = worksheet.Cells[row, col].Style.Font.Color;

              }
         }

enter image description here

1 个答案:

答案 0 :(得分:2)

文本可以通过两种方式在.xlsx文件中变为彩色。

  • 可以应用于单元格的样式(您尝试在上面使用的方法)
  • 该单元格可以包含&#34; Rich Text&#34;本身有色的内容

如果单元格包含多种颜色的文本,则它是后面的这些选项,因此我们必须使用.RichText属性来访问颜色。我们还可以测试以确定单元格是否包含具有.IsRichText属性的Rich文本。

以此工作簿为例:

enter image description here

然后在运行此代码时:

    static void Main(string[] args)
    {
        Dictionary<string, Color> dictionaryTextToColour = new Dictionary<string, Color>();

        var fInfo = new FileInfo(@"C:\Temp\sample.xlsx");
        using (var package = new ExcelPackage(fInfo))
        {

            var a1 = package.Workbook.Worksheets.First().Cells[1, 1];

            if (a1.IsRichText)
            {
                var richText = a1.RichText;
                dictionaryTextToColour = richText 
                    .ToDictionary(rt => rt.Text, rt => rt.Color); //NOT recommended to use a dictionary here
            }
        }

        foreach (var substring in dictionaryTextToColour.Keys)
        {
            Console.WriteLine(substring + ": " + dictionaryTextToColour[substring]);
        }
    }

我们看到了这个输出:

    Some: Color [Empty]
    TextW: Color [A=255, R=0, G=176, B=80]
    ithVarious: Color [A=255, R=0, G=32, B=96]
    Colour: Color [A=255, R=255, G=0, B=0]
    s: Color [Empty]

实现.RichText的{​​{1}}类型的ExcelRichTextCollection属性,因此我们也可以使用以下内容迭代每个文本段:

IEnumerable<ExcelRichText>

<强> N.B。我已经将颜色添加到用文本键入的字典中,因为这是原始问题中要求的但我不认为这是最好的数据结构,因为相同的子字符串可以用不同的颜色重复