【问题标题】:Programmatically adding conditional formatting in Excel 2007以编程方式在 Excel 2007 中添加条件格式
【发布时间】:2019-11-16 19:11:06
【问题描述】:

我想以编程方式使用 excel 2007 的条件格式功能。我有以下情况。

我有 6 列数字

A   B  C  D  E  F
100 25 25 15 20 50
....

if (C1/A1)*100 >= B1我必须把它涂成红色。相同的规则适用于 D1、E1、F1 列。

我在 excel 2007 中看到了条件格式功能。但我想要一些关于如何在 C# 代码中实现它的指示。

【问题讨论】:

  • 我很确定 Google 很清楚该做什么)

标签: c# excel excel-2007 excel-formula


【解决方案1】:

我假设您很乐意使用 Interop,因为您没有另外说。这是我用来在 Excel 中设置条件格式的方法。它假定您已经在名为 xlWorksheet 的变量中引用了您的 Worksheet

// Create a FormatCondition and add it to the specified range of cells, using the
// passed-in condition and cell colour

Excel.Range range = xlWorksheet.get_Range("C1", "C1");
Excel.FormatConditions fcs = range.FormatConditions;
Excel.FormatCondition fc = (Excel.FormatCondition)fcs.Add
    (Excel.XlFormatConditionType.xlExpression, Type.Missing, "=IF($C$1/$A$1)*100 >= $B$1");
Excel.Interior interior = fc.Interior;
interior.Color = ColorTranslator.ToOle(Color.Red);
interior = null;
fc = null;
fcs = null;
range = null;

我对您的预期用途有所猜测,但您可以对其进行修改以正确获取公式和单元格引用。

【讨论】:

  • 谢谢答案。但是当我使用代码时,我收到以下错误消息 =“找不到方法:'Microsoft.Office.Interop.Excel.FormatCondition Microsoft.Office.Interop.Excel.FormatConditions.Add(Microsoft.Office.Interop.Excel.XlFormatConditionType, System .Object, System.Object, System.Object)'。”
  • @Rajneesh 抱歉,我的代码在那一行有错字。我没有正确关闭支架。再试一次。如果仍然不起作用,请显示导致错误的语句。
  • 当我使用带有 3 个参数的 add 方法时,VS Intillesense 显示错误。所以,我使用了 FormatCondition formatCondition = (Excel.FormatCondition)formatConditions.Add(XlFormatConditionType.xlExpression, Type.Missing, "=D2/B2*100>=C2", Type.Missing);但是,在执行代码时,它显示了我在之前的评论中提到的错误。
  • @Rajneesh 我刚刚读到某些版本的 Interop 和 .NET 程序集存在一些后期绑定问题。您提到您使用的是 Excel 2007,但您引用了哪个版本的 Interop 程序集,您的目标是哪个版本的 .NET?
  • @Rajneesh 看看这个问题,这似乎与您遇到的问题相同:Excel Interop: Range.FormatConditions.Add throws MissingMethodException
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 2011-06-16
  • 1970-01-01
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多