【问题标题】:Read Excel Cell And Set Row Colour读取 Excel 单元格并设置行颜色
【发布时间】:2012-07-28 14:59:06
【问题描述】:

我正在使用 Com Interop 和 C#。我必须遍历一个 Excel 文件,在每一行中查找某些值(总是在第 2 列中)。对于某些值,我需要将行的背景颜色设置为红色。

我遇到了麻烦:

  1. 读取单元格 [i][2] 中第 i 行的值,并且
  2. 设置该行的背景颜色。

基本上我正在寻找这样的东西(这是我在谷歌搜索后能找到的最好的东西):

// ws is the worksheet
for (int i = 1; i <= ws.Rows.Count; i++)
{
    Range range = ws.Cells[i][2];
    int count = Convert.ToInt32(range.Value2.ToString());
    if (count >= 3)
    {
        Range chronic = ws.UsedRange.Rows[i];
        chronic.EntireRow.Cells.Interior.Color = 0xFF0000;
    }
}

这当然行不通。我无法通过阅读牢房的第一道障碍。任何建议表示赞赏。

【问题讨论】:

  • ws.UsedRange.Rows[i]; 应该是 ws.Rows[i]; Usedrange 并不总是从第一行开始。而Cells[i][2] 应该是Cells[i,2]
  • 您是否有理由必须使用另一个程序来执行此操作,而不是使用 Excel 中已内置的条件格式?您可能可以使用互操作添加条件格式,尽管我对互操作不够熟悉。

标签: c# excel com interop


【解决方案1】:

试试这个。代码假定第 2 列单元格中的值是一个数字。

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

Missing noValue = Missing.Value;
Excel.Range conditionalCell;
foreach (Excel.Range usedRange in ws.UsedRange.Rows)
{
    conditionalCell = usedRange.Cells[noValue, 2] as Excel.Range;
    if (Convert.ToInt32(conditionalCell.Value2) >= 3)
    {
        usedRange.Cells.Interior.Color = Excel.XlRgbColor.rgbRed;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 2016-04-28
    • 2017-05-02
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    相关资源
    最近更新 更多