使用Aspose.Cells库在C#中应用条件格式阴影以交替显示行和列。通过调整这些条件,您可以更好地控制单元格的外观。

Contents
[ ]

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

  • **ROW()**函数返回单元格引用的行号。如果省略引用参数,则假定引用是输入ROW函数的单元格地址。
  • **COLUMN()**函数返回单元格引用的列号。如果省略引用参数,则假定引用是输入COLUMN函数的单元格地址。
  • **MOD()**函数返回一个数字被除数除后的余数,函数的第一个参数是要查找余数的数值,第二个参数是用来除以数值参数的数。如果除数为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应用程序中的结果电子表格。

todo:image_alt_text

为了将底纹应用于交替列,您只需将公式**=MOD(ROW(),2)=0**更改为**=MOD(COLUMN(),2)=0**,即不再获取行索引,而是修改公式以检索列索引。 在这种情况下,生成的电子表格将如下所示。

todo:image_alt_text