在excel中获取单元格的内部颜色

时间:2013-08-13 14:10:33

标签: c# excel

我需要用excel中的错误数据突出显示细胞,我能够做到。但是一旦用户更正了数据并点击了验证按钮,内部颜色应该恢复为原始内部颜色。这不会发生。请指出错误。请提出确切的代码,因为我尝试过很多东西,但到目前为止还没有任何工作。

private void ValidateButton_Click(object sender, RibbonControlEventArgs e)
      {
          bool LeftUntagged = false;
          Excel.Workbook RawExcel = Globals.ThisAddIn.Application.ActiveWorkbook;
          Excel.Worksheet sheet = null;
          Excel.Range matrix = sheet.UsedRange;
          for (int x = 1; x <= matrix.Rows.Count; x++)
          {
              for (int y = 1; y <= matrix.Columns.Count; y++)
              {
                  string CellColor = sheet.Cells[x, y].Interior.Color.ToString();
                  if (sheet.Cells[x, y].Value != null && (Excel.XlRgbColor.rgbGold.Equals(sheet.Cells[x, y].Interior.Color) || Excel.XlRgbColor.rgbWhite.Equals(sheet.Cells[x, y].Interior.Color)))
                  {
                      sheet.Cells[x, y].Interior.Color = Color.Transparent;
                  }
              }
          }
      }

3 个答案:

答案 0 :(得分:0)

尝试:

sheet.Cells[x, y].Interior.ColorIndex =  -4142;  //xlNone

答案 1 :(得分:0)

执行此操作的方法是使用ColorIndex。可以在Adding Color to Excel 2007 Worksheets by Using the ColorIndex Property找到完整的值列表。

在代码中,只需使用上面链接中图1中的索引。

// For example
sheet.Cells[x, y].Interior.ColorIndex = 3; // Set to RED

如果您需要比较颜色,只需比较ColorIndex

即可

答案 2 :(得分:0)

我实现了我想要做的事情。这是解决方案:

private void ValidateButton_Click(object sender, RibbonControlEventArgs e)
      {
          bool LeftUntagged = false;
          Excel.Workbook RawExcel = Globals.ThisAddIn.Application.ActiveWorkbook;
          Excel.Worksheet sheet = null;
          Excel.Range matrix = sheet.UsedRange;
          for (int x = 1; x <= matrix.Rows.Count; x++)
          {
              for (int y = 1; y <= matrix.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;
                  }
              }
          }
      }