本内容丰富的指南介绍了如何在 C# 中的 Excel 中应用条件格式。它包含编写此应用程序时要完成的一组编程任务以及用于在 C# 中的 Excel 中添加条件格式的示例代码。您还将了解根据应用程序要求添加具有不同格式的多个条件的过程。
在 C# 中的 MS Excel 中添加条件格式的步骤
- 设置环境以使用 Aspose.Cells for .NET 应用条件格式
- 创建一个空的 workbook 并访问其第一个默认工作表
- 创建一个 conditional formatting collection 对象并访问其引用
- 创建单元格区域并将其添加到条件格式集合对象中
- 创建格式条件,设置其所需参数,并将其添加到上述集合中
- 为新创建的条件设置所需的格式
- 添加条件格式后保存输出 Excel 文件
这些步骤总结了在 C#* 电子表格中设置*条件格式的过程。该过程首先创建一个工作簿,访问其第一个工作表,并将条件格式设置对象添加到所选工作表的 ConditionalFormattings 集合中。在接下来的步骤中,为此条件格式集合对象定义单元格区域,然后创建条件并设置其格式样式,然后保存生成的 Excel 文件。
使用 C# 在 Excel 中创建条件格式的代码
using Aspose.Cells; | |
using System; | |
using System.Drawing; | |
class Program | |
{ | |
static void Main(string[] args) // Apply conditional formatting in C# | |
{ | |
// Set the license | |
new License().SetLicense("Aspose.Total.Product.Family.lic"); | |
// Create a Workbook for conditional formatting and access its first sheet | |
Workbook spreadsheet = new Workbook(); | |
Worksheet sheet = spreadsheet.Worksheets[0]; | |
// Initiate a conditional formatting object | |
int indexCondFormatting = sheet.ConditionalFormattings.Add(); | |
FormatConditionCollection fcs = sheet.ConditionalFormattings[indexCondFormatting]; | |
// Create a cell range and add to the format conditions collection | |
CellArea cellArea = new CellArea() | |
{ | |
StartRow = 0, | |
EndRow = 10, | |
StartColumn = 0, | |
EndColumn = 1 | |
}; | |
fcs.AddArea(cellArea); | |
// Create the first condition and get the reference to it | |
int conditionIndex = fcs.AddCondition( | |
FormatConditionType.CellValue, OperatorType.Between, "25", "100"); | |
FormatCondition formatCondition = fcs[conditionIndex]; | |
// Set the desired formatting | |
formatCondition.Style.BackgroundColor = Color.Red; | |
// Save the workbook with a conditional formatting | |
spreadsheet.Save("output.xls"); | |
Console.WriteLine("Done"); | |
} | |
} |
此示例代码演示了 Excel 中基于 C# 单元格值的条件格式的实现。您可以根据需要添加任意数量的条件,方法是重复使用 AddCondition() 方法添加条件的步骤,然后为其设置所需的格式。此代码创建一个 Excel 文件,一旦单元格的值设置在 25 到 100 之间,自定义单元格区域中的单元格就会自动变为红色。
本示例教程教我们在 C#* 中应用基于单元格值的 *Excel 条件格式。如果您想了解在工作簿中插入切片器的过程,请参阅有关 如何使用 C# 在 Excel 中插入切片器 的文章。