使用Aspose.Cells库在C#中应用条件格式阴影以交替显示行和列。通过调整这些条件,您可以更好地控制单元格的外观。
Contents
[
Hide
]
Aspose.Cells API 提供了为 Worksheet 对象添加和操作条件格式规则的手段。这些规则可以多种方式定制,以根据条件或规则实现理想的格式。本文章将演示如何使用 Aspose.Cells for Node.js via C++ API 结合条件格式规则和 Excel 内置函数,对奇偶行和列进行阴影填充。
本文使用Excel内置函数,如ROW、COLUMN和MOD。以下是这些函数的一些详细信息,以便更好地理解提供的代码片段。
- ROW() 函数返回单元格引用的行号。如果省略引用参数,则假定引用为输入 ROW 函数的单元格地址。
- COLUMN() 函数返回单元格引用的列号。如果省略引用参数,则假定引用为输入 COLUMN 函数的单元格地址。
- **MOD()**函数返回一个数字被除数除后的余数,函数的第一个参数是要查找余数的数值,第二个参数是用来除以数值参数的数。如果除数为0,则会返回#DIV/0!错误。
让我们开始编写一些代码,利用 Aspose.Cells for Node.js via C++ API 实现此目标。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require("path"); | |
const AsposeCells = require("aspose.cells.node"); | |
// The path to the documents directory. | |
const dataDir = path.join(__dirname, "data"); | |
// Create an instance of Workbook or load existing | |
const book = new AsposeCells.Workbook(); | |
// Access the Worksheet on which desired rule has to be applied | |
const sheet = book.getWorksheets().get(0); | |
// Add FormatConditions to the instance of Worksheet | |
let idx = sheet.getConditionalFormattings().add(); | |
// Access the newly added FormatConditions via its index | |
const conditionCollection = sheet.getConditionalFormattings().get(idx); | |
// Define a CellsArea on which conditional formatting will be applicable | |
// The code creates a CellArea ranging from A1 to I20 | |
const area = AsposeCells.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(AsposeCells.FormatConditionType.Expression); | |
// Access the newly added FormatCondition via its index | |
const formatCondition = conditionCollection.get(idx); | |
// Set the formula for the FormatCondition | |
formatCondition.setFormula1("=MOD(ROW(),2)=0"); | |
// Set the background color and pattern for the FormatCondition's Style | |
formatCondition.getStyle().setBackgroundColor(AsposeCells.Color.Blue); | |
formatCondition.getStyle().setPattern(AsposeCells.BackgroundType.Solid); | |
// Save the result on disk | |
book.save(path.join(dataDir, "output_out.xlsx")); |
以下快照显示了加载到Excel应用程序中的结果电子表格。
![]() |
---|
为了将底纹应用于交替列,您只需将公式**=MOD(ROW(),2)=0**更改为**=MOD(COLUMN(),2)=0**,即不再获取行索引,而是修改公式以检索列索引。
在这种情况下,生成的电子表格将如下所示。
![]() |
---|