简体   繁体   English

在 openpyxl 中,有没有办法查看单元格应用了哪些条件格式规则?

[英]In openpyxl, is there a way to see what conditional formatting rule(s) are applied to a cell?

I'm using openpyxl 2.5.6 and py 3.7.0.我正在使用 openpyxl 2.5.6 和 py 3.7.0。 My goal is to read an Excel workbook and print both the contents and the formatting of each cell into a CSV.我的目标是读取 Excel 工作簿并将每个单元格的内容和格式打印到 CSV 中。 For instance, if a cell is blue with text "Data" then I would prepend a tag of "[blu]" to the cell value, printing to the CSV as "[blu]Data" and do this likewise with a cell that's bolded and for other fill colors, etc.例如,如果一个单元格是蓝色的,带有文本“Data”,那么我会在单元格值前面加上一个“[blu]”标签,打印到 CSV 中作为“[blu]Data”,同样地对加粗的单元格执行此操作以及其他填充颜色等。

I can do this perfectly fine for cells with static formatting, but not with conditional formatting.对于具有静态格式但不具有条件格式的单元格,我可以完美地做到这一点。 My issue is that I don't know how to tell if a conditional formatting rule is applied.我的问题是我不知道如何判断是否应用了条件格式规则。 I found the conditional_formatting._cf_rules dict, but I'm only seeing attributes like formula, priority, dxfId, and the dxf rules itself.我找到了conditional_formatting._cf_rules字典,但我只看到公式、优先级、dxfId 和 dxf 规则本身等属性。 I want to believe that the data of whether a cf rule is applied or not might stored somewhere, but I cannot find where it might be.我想相信是否应用 cf 规则的数据可能存储在某个地方,但我找不到它可能在哪里。

My code thus far looks something like this.到目前为止,我的代码看起来像这样。

from openpyxl import load_workbook

wb = load_workbook('Workbook_Name.xlsx', data_only = True)
ws = wb['Worksheet1']

# Code that shows me each cf rule's formula, fill type, priority, etc
cellrangeslist = list(ws.conditional_formatting._cf_rules)
for cellrange in cellrangeslist:
    print('{:30s}{:^10s}{:30s}'.format('----------------------------',str(cellrange.sqref),'----------------------------'))
    for i in cellrange.cfRule:
        print('{:10s}{:8s}{:40s}{:10s}{:10s}'.format(str(i.dxf.fill.bgColor.index), str(i.dxf.fill.bgColor.type), str(i.formula), str(i.stopIfTrue), str(i.priority)))


# This is where I want to be able to identify which cf rule is applied to a given cell
#
#
#

# Code that interprets cell styling into appropriate tags, e.g.
for r in ws.iter_rows(min_row = ws.min_row, max_row = ws.max_row, min_col = ws.min_column, max_col = ws.max_column):
     for cell in r:
          if cell.font.b == True:
                 cell.value = "[bold]"+cell.value

# Code to write each cell as a string literal to a CSV file
#
#
#

My Excel file looks like this ,我的 Excel 文件看起来像这样

  • A1 == 1234 A1 == 1234
  • B1 == 1235 B1 == 1235
  • C1 == '=A1-B1' C1 == '=A1-B1'

And my cf rules look like this ,我的 cf 规则是这样的,

  • Formula: =$A1 - $B1 < 0, Format: [red fill], Applies to: =$C$1公式:=$A1 - $B1 < 0,格式:[红色填充],适用于:=$C$1
  • Formula: =$A1 - $B1 > 0, Format: [green fill], Applies to: =$C$1公式:=$A1 - $B1 > 0,格式:[绿色填充],适用于:=$C$1

The console output I receive from the above code is我从上面的代码收到的控制台输出是

----------------------------      C1    ----------------------------
FF92D050  rgb     ['$A1-$B1>0']                           None      2
FFFF0000  rgb     ['$A1-$B1<0']                           None      1

The output shows the rules are properly there, but I'm wanting to know if there's a way to tell which of these rules, if any, are actually applied to the cell.输出显示规则正确存在,但我想知道是否有办法判断这些规则中的哪些(如果有)实际应用于单元格。

I have a growing suspicion that it's something calculated on runtime of Excel, so my alternative is to write an Excel formula interpreter, but I'm really hoping to avoid that by just about any means as I'm not sure I have the skill to do it.我越来越怀疑它是在 Excel 的运行时计算出来的,所以我的替代方法是编写一个 Excel 公式解释器,但我真的希望通过任何方式避免这种情况,因为我不确定我是否有能力做吧。

If you don't find a better option, following on from my comment this is an example of what you could do with Xlwings.如果您找不到更好的选择,请按照我的评论,这是您可以使用 Xlwings 执行的操作的示例。

For the example output shown, A1 is a higher number than B1 so cell C1 is green.对于所示的示例输出,A1 的数字大于 B1,因此单元格 C1 为绿色。
A1 = 1236 A1 = 1236
B1 = 1235 B1 = 1235
If the A1 is changed back to 1234, C1 colour returns to red and if the same code is run after the workbook is saved the 'Colour applied to conditional format cell:' will be for 'Conditional Format 1' ie red如果 A1 改回 1234,C1 颜色返回红色,如果在保存工作簿后运行相同的代码,“应用于条件格式单元格的颜色:”将用于“条件格式 1”,即红色

import xlwings as xw
from xlwings.constants import RgbColor


def colour_lookup(cfc):
    cell_colour = (key for key, value in colour_dict.items() if value == cfc)
    for key in cell_colour:
        return key


colour_dict = { key: getattr(RgbColor, key) for key in dir(RgbColor) if not key.startswith('_') }


wb = xw.Book('test.xlsx')
ws = wb.sheets('Sheet1')

cf = ws['C1'].api.FormatConditions
print("Number of conditional formatting rules: " + str(cf._inner.Count))
print("Colour applied to conditional format cell:\n\tEnumerated: " +
      str(cf._inner.Parent.DisplayFormat.Interior.Color))
print("\tRGBColor: " + colour_lookup(cf._inner.Parent.DisplayFormat.Interior.Color))

print("------------------------------------------------")

for idx, cf_detail in enumerate(cf, start=1):
    print("Conditional Format " + str(idx))
    print(cf_detail._inner.Formula1)
    print(cf_detail._inner.Interior.Color)
    print("\tRGBColor: " + colour_lookup(cf_detail._inner.Interior.Color))
    print("")

Output输出

Number of conditional formatting rules: 2
Colour applied to conditional format cell:
    Enumerated: 32768.0
    RGBColor: rgbGreen
------------------------------------------------
Conditional Format 1
=$A1-$B1<0
255.0
    RGBColor: rgbRed

Conditional Format 2
=$A1-$B1>0
32768.0
    RGBColor: rgbGreen

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

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