阅读工作表并保留条件格式

nit*_*tin 5 python excel openpyxl

我正在尝试使用 openpyxl 读取 excel 工作表。当我像这样阅读时,我想我会丢失工作表中的条件格式信息:

xl = openpyxl.load_workbook(filename)
Run Code Online (Sandbox Code Playgroud)

当我读取文件中的所有单元格并保存时。我得到一个电子表格,其中没有实现任何条件格式。

我可以在http://openpyxl.readthedocs.org/en/latest/formatting.html找到许多向电子表格添加条件格式的方法

但是我找不到在现有工作表中读取条件格式信息的方法。

我用于读写的具体代码是,

import openpyxl as xl

xlf = xl.load_workbook(r'd:\test\book1.xlsx')
sh = xlf.get_sheet_by_name('Sheet1')
allcells = sh.get_cell_collection()

wb = xl.Workbook()
ws = wb.create_sheet()

for c in allcells:
    row = c.row
    col = xl.cell.column_index_from_string(c.column)
    new_cell = ws.cell(row=row, column=col)
    new_cell.value = c.value
    new_cell.style = c.style.copy()

ws.title = 'test'
wb.save(r'd:\test\book1w.xlsx')
Run Code Online (Sandbox Code Playgroud)

Ale*_*dro 5

我真的很接近,但我无法保持颜色。仍然存在错误,但如果不是填充选项,至少以下内容确实添加了保留条件格式规则:

for range_string in sh.conditional_formatting.cf_rules:
    for cfRule in sh.conditional_formatting.cf_rules[range_string]:
        ws.conditional_formatting.add(range_string, cfRule)
Run Code Online (Sandbox Code Playgroud)

使用这种衬垫实现相同的效果(但最终结果相同):

ws.conditional_formatting.update(sh.conditional_formatting.cf_rules)
Run Code Online (Sandbox Code Playgroud)

现在,如果您Manage Rules在 excel 中打开规则,所有规则都在那里,但是当您打开文件时,它需要自动修复并且我失去了颜色。这是超级有用的日志(此处带有讽刺意味):

<repairedRecord>Repaired Records: Conditional formatting from /xl/worksheets/sheet2.xml</repairedRecord></repairedRecords>
Run Code Online (Sandbox Code Playgroud)

当我尝试conditional_formatting像这样直接复制的三个属性时,我得到了类似的结果:

ws.conditional_formatting.cf_rules = sh.conditional_formatting.cf_rules.copy()
ws.conditional_formatting.max_priority = sh.conditional_formatting.max_priority
ws.conditional_formatting.parse_rules = sh.conditional_formatting.parse_rules.copy()
Run Code Online (Sandbox Code Playgroud)

我一直在寻找想法的源代码

编辑

有一个非常简单的选择。不要创建一个全新的工作簿和工作表并从头开始处理它们。只需根据需要修改原始文件,然后将其另存为不同的名称。或者,您甚至可以先将其另存为不同的名称以创建副本,然后再修改副本。这将保留所有格式规则。