C# 条件格式化Excel

标签 c# excel formatting excel-2007 excel-interop

在我的项目中,我有根据单元格值条件设置单元格背景颜色格式的代码,如下所示:

//if value is 1 than colorIndex is 3;
Excel.FormatCondition condition = colorRange.FormatConditions.Add(
    Type: Excel.XlFormatConditionType.xlTextString, 
    Operator: Excel.XlFormatConditionOperator.xlEqual,
    Formula1: "=1");
condition5.Interior.ColorIndex = 3;

这个条件可以正常工作,但是下面代码中的条件不起作用:

//if value is Red Color than colorIndex is 3;
Excel.FormatCondition condition = colorRange.FormatConditions.Add(
    Type: Excel.XlFormatConditionType.xlTextString, 
    Operator: Excel.XlFormatConditionOperator.xlEqual,
    Formula1: "=Red Color");
condition5.Interior.ColorIndex = 3;

我收到的错误消息是“参数不正确”

我做错了什么?

最佳答案

我认为错误来自于您传递的 Formula1 参数是一个公式。这意味着它应该像您在 Excel 单元格中手动编写的公式一样编写。这意味着当您编写“红色”作为参数时,Excel 会尝试将其转换为公式,但语法错误,并会给出错误。

您可以尝试只输入“=Red”(没有字符串的颜色部分),它不会给您错误,但无论如何它都不起作用,因为它会比较单元格中的值包含在名为 Red 的单元格中(我想您的工作表中没有这样的单元格)。

解决方案是以这种方式将 "放在字符串周围:

Excel.FormatCondition condition = colorRange.FormatConditions.Add(
    Type: Excel.XlFormatConditionType.xlTextString, 
    Operator: Excel.XlFormatConditionOperator.xlEqual,
    Formula1: "=\"Red Color\"");

关于C# 条件格式化Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10843470/

相关文章:

c# - 为 .NET MVC 中的 ObjectContext 设计回退的最佳方法是什么

c# - 使用 .Net Interop 从 Excel 获取 DateTime 值时缺少毫秒数

vba - 我一生都无法弄清楚导致此不匹配错误 VBA Excel 的原因是什么?

excel - 自动筛选日期时间值 - 本地小数点问题

c# - 未使用 MVC 3 自定义 ModelBinder

C# 添加 HyperLinkColumn 到 GridView

java - 如何使用 POI 测试单元格是否符合 ConditionalFormattingRule 中定义的规则?

html - 每当我调整编辑器窗口的大小时,如何阻止代码行自动转移到下一行?

string - 使用不正确的字符串格式时如何从编译器获取消息

c# - 将字符串映射到实体以与通用方法一起使用