Применение условного форматирования на листах

Использование Aspose.Cells для применения условного форматирования на основе значения Cell

  1. Загрузите и установите Aspose.Cells.
  2. Скачать Aspose.Cells for .NET.
  3. Установите его на свой компьютер разработки. Все компоненты Aspose после установки работают в ознакомительном режиме. Режим оценки не имеет ограничения по времени и только вставляет водяные знаки в создаваемые документы.
  4. Создать проект. Запустите Visual Studio.NET и создайте новое консольное приложение. В этом примере создается консольное приложение C#, но вы также можете использовать VB.NET.
  5. Добавить ссылки. Добавьте ссылку на Aspose.Cells в свой проект, например добавьте ссылку на ….\Program Files\Aspose\Aspose.Cells\Bin\Net1.0\Aspose.Cells.dll
    • Применять условное форматирование на основе значения ячейки. Ниже приведен код, используемый для выполнения задачи. Я применяю условное форматирование к ячейке.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
// Adds an empty conditional formatting
int index = sheet.ConditionalFormattings.Add();
FormatConditionCollection fcs = sheet.ConditionalFormattings[index];
// Sets the conditional format range.
CellArea ca = new CellArea();
ca.StartRow = 0;
ca.EndRow = 0;
ca.StartColumn = 0;
ca.EndColumn = 0;
fcs.AddArea(ca);
// Adds condition.
int conditionIndex = fcs.AddCondition(FormatConditionType.CellValue, OperatorType.Between, "50", "100");
// Sets the background color.
FormatCondition fc = fcs[conditionIndex];
fc.Style.BackgroundColor = Color.Red;
// Saving the Excel file
workbook.Save(dataDir+ "output.out.xls", SaveFormat.Auto);

Когда приведенный выше код выполняется, условное форматирование применяется к ячейке «A1» на первом рабочем листе выходного файла (output.xls). Условное форматирование, применяемое к A1, зависит от значения ячейки. Если значение ячейки A1 находится в диапазоне от 50 до 100, цвет фона будет красным из-за примененного условного форматирования.

Использование Aspose.Cells для применения условного форматирования на основе формулы

  1. Применение условного форматирования в зависимости от формулы (фрагмент кода) Ниже приведен код для выполнения задачи. Он применяет условное форматирование к B3.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
// Adds an empty conditional formatting
int index = sheet.ConditionalFormattings.Add();
FormatConditionCollection fcs = sheet.ConditionalFormattings[index];
// Sets the conditional format range.
CellArea ca = new CellArea();
ca = new CellArea();
ca.StartRow = 2;
ca.EndRow = 2;
ca.StartColumn = 1;
ca.EndColumn = 1;
fcs.AddArea(ca);
// Adds condition.
int conditionIndex = fcs.AddCondition(FormatConditionType.Expression);
// Sets the background color.
FormatCondition fc = fcs[conditionIndex];
fc.Formula1 = "=IF(SUM(B1:B2)>100,TRUE,FALSE)";
fc.Style.BackgroundColor = Color.Red;
sheet.Cells["B3"].Formula = "=SUM(B1:B2)";
sheet.Cells["C4"].PutValue("If Sum of B1:B2 is greater than 100, B3 will have RED background");
// Saving the Excel file
workbook.Save(dataDir+ "output.out.xls", SaveFormat.Auto);

Когда приведенный выше код выполняется, условное форматирование применяется к ячейке «B3» на первом рабочем листе выходного файла (output.xls). Применяемое условное форматирование зависит от формулы, которая вычисляет значение «B3» как сумму B1 и B2.