使用条件格式将底纹应用于交替行和列

Contents
[ ]

本文使用 Excel 的内置函数,如 ROW、COLUMN 和 MOD。下面是这些函数的一些详细信息,以便更好地理解前面提供的代码片段。

  • **排()**函数返回单元格引用的行号。如果省略引用参数,则假定引用是输入 ROW 函数的单元格地址。
  • **柱子()**函数返回单元格引用的列号。如果省略引用参数,则假定引用是输入 COLUMN 函数的单元格地址。
  • **模组()**函数返回数字除以除数后的余数,其中函数的第一个参数是要求余数的数值,第二个参数是用于除以数字参数的数字。如果除数为 0,则返回 #DIV/0!错误。

让我们在 Aspose.Cells for .NET API 的帮助下开始编写一些代码来实现这个目标。

// 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 an instance of Workbook or load existing
var book = new Workbook();
// Access the Worksheet on which desired rule has to be applied
var sheet = book.Worksheets[0];
// Add FormatConditions to the instance of Worksheet
int idx = sheet.ConditionalFormattings.Add();
// Access the newly added FormatConditions via its index
var conditionCollection = sheet.ConditionalFormattings[idx];
// Define a CellsArea on which conditional formatting will be applicable
// The code creates a CellArea ranging from A1 to I20
var area = CellArea.CreateCellArea("A1", "I20");
//Add area to the instance of FormatConditions
conditionCollection.AddArea(area);
// Add a condition to the instance of FormatConditions
// For this case, the condition type is expression, which is based on some formula
idx = conditionCollection.AddCondition(FormatConditionType.Expression);
// Access the newly added FormatCondition via its index
FormatCondition formatCondirion = conditionCollection[idx];
// Set the formula for the FormatCondition
// Formula uses the Excel's built-in functions as discussed earlier in this article
formatCondirion.Formula1 = @"=MOD(ROW(),2)=0";
// Set the background color and patter for the FormatCondition's Style
formatCondirion.Style.BackgroundColor = Color.Blue;
formatCondirion.Style.Pattern = BackgroundType.Solid;
// Save the result on disk
book.Save(dataDir + "output_out.xlsx");

以下快照显示了在 Excel 应用程序中加载的结果电子表格。

待办事项:图片_替代_文本

为了将阴影应用于替代列,您所要做的就是更改公式**=MOD(行(),2)=0**作为**=MOD(列(),2)=0** , 那是;不是获取行索引,而是修改公式以检索列索引。 在这种情况下,生成的电子表格将如下所示。

待办事项:图片_替代_文本