使用 C# 以编程方式格式化值之间的 Excel 行
Formatting Excel rows between values programmatically with C#
我在一个项目中工作,我必须生成一个带有格式条件的 Excel。我能够用相等的值来做到这一点(例如:B2 = "Correct Value")但在某些情况下我必须检查该值是否在两个值之间(例如:“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"。
谢谢,
米格尔.
感谢我的超级智慧,我能够解决这个问题。我需要的代码是:
format[i] = (FormatCondition)(xlWorksheet.get_Range($"B{i + 1}", Type.Missing).FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlBetween, $"={qMax[i - 1]}", $"={qMin[i - 1]}"));
我在一个项目中工作,我必须生成一个带有格式条件的 Excel。我能够用相等的值来做到这一点(例如:B2 = "Correct Value")但在某些情况下我必须检查该值是否在两个值之间(例如:“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"。
谢谢, 米格尔.
感谢我的超级智慧,我能够解决这个问题。我需要的代码是:
format[i] = (FormatCondition)(xlWorksheet.get_Range($"B{i + 1}", Type.Missing).FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlBetween, $"={qMax[i - 1]}", $"={qMin[i - 1]}"));