如何使用C#获取Excel单元格的背景颜色?

6

我想使用C#获取Excel单元格的背景颜色,但是我找不到方法。

  1. which library shall I use ? microsoft.office.tools.excel.workbook.aspx or microsoft.office.interop.excel ? what's the differents?

  2. I have tried following code but get no luck:

    using Excel = Microsoft.Office.Interop.Excel;
    
    private void button1_Click(object sender, EventArgs e)
    {
        ofd.Filter = "xlsx|*.xlsx|xls|*.xls";
    
        if(ofd.ShowDialog() == DialogResult.OK)
        {
            textBox2.Text = ofd.FileName;
            Excel.Application excel = new Excel.Application();
            Excel.Workbook wb = excel.Workbooks.Open(textBox2.Text);
            Excel.Worksheet ws = wb.Sheets[1];
            Excel.Range xlRange = ws.Cells[0, 0];
            Debug.WriteLine("===" + xlRange.Interior.Color);
        }
    }
    

我认为这里的真正问题在于示例代码对行和列使用了从零开始的索引(即ws.Cells [0,0])。如果您查看了第1行,A/1列(即ws.Cells [1,1]),那么对Range.Interior.Color的调用将会按预期返回一个double。 - Mark McClelland
4个回答

6

有一个很好的库叫做EPPlus,可以让你更轻松地处理Excel。你可以在NuGet上找到它。
使用以下代码获取颜色:

var x = sheet.Cells[rowIndex, colIndex].Style.Fill.BackgroundColor;

使用以下代码设置颜色:

sheet.Cells[rowIndex, colIndex].Style.Fill.SetCellsColor( Color.Yellow );


2

最简单的解决方案:

 private void Get_Colors()
  {
      Excel.Workbook excel = Globals.ThisAddIn.Application.ActiveWorkbook;
      Excel.Worksheet sheet = null;
      Excel.Range ran = sheet.UsedRange;
      for (int x = 1; x <= ran.Rows.Count; x++)
      {
          for (int y = 1; y <= ran.Columns.Count; y++)
          {
              string CellColor = sheet.Cells[x, y].Interior.Color.ToString(); //Here I go double value which is converted to string.
              if (sheet.Cells[x, y].Value != null && (CellColor == Color.Transparent.ToArgb().ToString() || **CellColor == Excel.XlRgbColor.rgbGold.GetHashCode().ToString()**))
              {
                  sheet.Cells[x, y].Interior.Color = Color.Transparent;
              }
          }
      }
  }

1
但是我尝试过了,在Excel.Range ran中没有ran.Rows.Count - armnotstrong
你是否缺少任何引用? - Aousaf Rashid
我正在使用 using Excel = Microsoft.Office.Interop.Excel; 来包含库。 - armnotstrong
@HéctorManuelMartinezDurán,男士,你怎么成为我的粉丝的?!!!我做了什么让你如此崇拜我?!! - Aousaf Rashid
@zackraiyan 发生的情况是我关闭了 FB 的标签页去吃午餐 ;-) - Héctor M.
显示剩余4条评论

1

这里有一个使用closed.xml的答案。它是开源的,并且可以与现代Excel表格一起使用。

IXLWorkbook wb = new XLWorkbook("C:\File_path_to_excel_file"); // Replace with your file path
IXLWorksheet ws = wb.Worksheet("SheetName") // Put your sheet name here
int backgroundColor = ws.Cell(rowIndex, colIndex).Style.Fill.BackgroundColor.Color.ToArgb(); // Gives the Argb values for the cell's background. Replace rowIndex and colIndex with the index numbers of the cell you want to check

通常,未上色的单元格的Argb颜色为16777215。

1
这很简单,只需要按照以下步骤操作:
using Excel = Microsoft.Office.Interop.Excel;
var cellColor  = sheet.Cells[rowIndex, colIndex].Style.Fill.BackgroundColor;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接