这个简短的教程将指导 如何使用 Python 基于单元格值在 Excel 中应用条件格式。它包含使用给定链接处的资源设置开发环境的详细信息、描述逻辑的步骤列表以及使用 Python 基于文本进行条件格式化的可运行示例代码。在使用此示例代码时,您还将了解不同类型的条件和其他自定义。
使用 Python 在 Excel 中应用条件格式的步骤
- 设置环境以通过 Java 使用 Aspose.Cells for Python via Java 格式化单元格
- 创建一个 Workbook 并访问要完成条件格式的第一个工作表
- 在所选工作表中创建一个 conditional formatting 实例并获取其访问权限
- 创建要应用此条件的单元格区域并将其设置为格式化对象
- 通过设置FormatConditionType和范围为条件格式化对象添加条件
- 设置各个条件的背景颜色并保存生成的工作簿
这些步骤定义了使用 Python 在 Excel 中添加条件格式的过程。该过程首先创建一个工作簿,从中访问工作表,然后创建空的条件格式。在后续步骤中,为条件格式化设置不同的参数,例如单元格区域、要检查的条件以及满足条件时要执行的格式化。
使用 Python 应用条件格式的代码
import jpype | |
import asposecells | |
jpype.startJVM() | |
from asposecells.api import ( | |
License, | |
Workbook, | |
CellArea, | |
FormatConditionType, | |
OperatorType, | |
Color | |
) | |
# Instatiate a license | |
license = License() | |
license.setLicense("Aspose.Total.lic") | |
# Create a Workbook | |
wb = Workbook() | |
ws = wb.getWorksheets().get(0) | |
# Create a conditional formatting object and access it | |
index = ws.getConditionalFormattings().add() | |
fcs = ws.getConditionalFormattings().get(index) | |
# Set cells range for applying to formatting | |
ca = CellArea() | |
ca.StartRow = 0 | |
ca.EndRow = 10 | |
ca.StartColumn = 0 | |
ca.EndColumn = 1 | |
fcs.addArea(ca) | |
# Create a condition and access it | |
conditionIndex = fcs.addCondition( | |
FormatConditionType.CELL_VALUE,OperatorType.BETWEEN, "17", "50") | |
formatCondition = fcs.get(conditionIndex) | |
# Set background color as formatting | |
formatCondition.getStyle().setBackgroundColor(Color.getGreen()) | |
# Save the formatted workbook | |
wb.save("output.xls") | |
print("Done") | |
jpype.shutdownJVM() |
此示例代码演示了使用 Python* 根据单元格值在 Excel 中应用*条件格式的过程。它演示了基于用户设置的一系列值的格式。但是,您可以使用其他格式条件类型,例如 EXPRESSION、COLOR_SCALE、DATA_BAR 和 CONTAINS_TEXT 来列出一些。类似地,其他运算符类型可以是 EQUAL、GREATER_THAN、GREATER_OR_EQUAL 和 NOT_BETWEEN 等。
本教程教我们使用 Python* 在电子表格中设置*条件格式。如果您想在 Excel 中应用过滤器,请参阅有关 如何使用Python在Excel中应用过滤器 的文章。