简体   繁体   English

如何在openpyXL中为特定列(D)添加下拉按钮并在选择一个选项时更改特定单元格的背景颜色

[英]How to add drop down button for particular column (D) in openpyXL and change the background color of particular cell when one option is selected

Using OpenPyXl , can we have privilege to add drop down button (High and Low) like we have in XlsxWriter data_validation() ;使用OpenPyXl ,我们可以像在XlsxWriter data_validation()那样有权限添加下拉按钮(高和低) XlsxWriter data_validation() and add background color Green to entire row when High is selected and Red if Low is selected?并在选择High时向整行添加背景颜色绿色,如果选择Low则向整行添加背景颜色?

In XlsxWriter we have:XlsxWriter我们有:

format_green = workbook.add_format({'bg_color': 'green'})
format_red = workbook.add_format({'bg_color': 'red'})

# Apply the data validation rule
worksheet.data_validation('D2:D5', {'validate': 'list',
                            'source': ['High','Low']})

# Apply the conditional formating rules
worksheet.conditional_format('A2:D5', {'type': 'formula',
                            'criteria': '=$D2="High"',
                            'format': format_green})

worksheet.conditional_format('A2:D5', {'type': 'formula',
                            'criteria': '=$D2="Low"',

                            'format': format_red})

Do we have similar functionality when using OpenPyXl ?我们在使用OpenPyXl时有类似的功能吗?

Yes, there is both Conditional Formatting and Data Validation in OpenPyXl .是的,在OpenPyXl有条件格式数据验证

Here is an example of Conditional Formatting:以下是条件格式的示例:

import openpyxl
from openpyxl import *
from openpyxl.formatting import Rule
from openpyxl.styles import Font, PatternFill, Border, Alignment
from openpyxl.formatting.rule import CellIsRule

wb = load_workbook("./document.xlsx")
ws = wb.active

ws.conditional_formatting.add('A2:D5', CellIsRule(operator='lessThan', formula=['0'],font = Font(color = '00FF0000')))

wb.save('document.xlsx')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM