使用C#编程地在值之间设置Excel行的格式

mrzz3bfm  于 2023-05-19  发布在  C#
关注(0)|答案(1)|浏览(143)

我在一个项目工作,我必须生成一个Excel格式的条件。我可以用equals值来实现(例如:B2 =“正确值”),但在某些情况下,我必须检查该值是否介于两个值之间(例如:“2 < B2 < 4“)我有这样的代码:

FormatCondition[] format = new FormatCondition[datos.Length];
            Microsoft.Office.Interop.Excel.Range[] cells = new Range[datos.Length];
            for (int i = 1; i < datos.Length; i++)
            {
                string condition = "";
                if (qTipo[i - 1] == "Num" && qMax[i - 1] != "" && qMin[i - 1] != "")
                { // DOES NOT WORK
                    condition = $"=Y(B{i + 1}<{qMax[i - 1]};B{i + 1}>{qMin[i - 1]})"; // THIS RETURNS "=Y(B4<6;B4>4)"
                    format[i] = (FormatCondition)(xlWorksheet.get_Range($"B{i + 1}",
                    Type.Missing).FormatConditions.Add(XlFormatConditionType.xlExpression, Type.Missing,
                    condition));
                }
                else
                {   //WORKS
                    condition = $"=B{i + 1}=\"{qCorrecto[i - 1]}\""; // THIS RETURNS "=B2="Correct Value""
                    format[i] = (FormatCondition)(xlWorksheet.get_Range($"B{i + 1}",
                    Type.Missing).FormatConditions.Add(XlFormatConditionType.xlExpression, Type.Missing,
                    condition));
                }
                format[i].Interior.Color = 0x0000FF00;
                datos[i] = new String[2];
                datos[i][0] = qPregunta[i - 1];
                datos[i][1] = "";
            }

当我执行这段代码时,它在Add语句上给我“Invalid argument exception”。
谢谢米格尔

nbysray5

nbysray51#

多亏了我的聪明才智,我才能解决这个问题。我需要的代码是:

format[i] = (FormatCondition)(xlWorksheet.get_Range($"B{i + 1}", Type.Missing).FormatConditions.Add(XlFormatConditionType.xlC‌​ellValue, XlFormatConditionOperator.xlBetween, $"={qMax[i - 1]}", $"={qMin[i - 1]}"));

相关问题