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

reading worksheet and preserving conditional formatting

我正在尝试使用 openpyxl 阅读 excel 作品sheet。我想我在 sheet 中丢失了条件格式信息,当我这样阅读它时:

xl = openpyxl.load_workbook(filename)

当我读取文件中的所有单元格并保存时。我得到一个 spreadsheet,其中实施了条件格式 none。

我可以在以下位置找到许多向传播添加条件格式的方法sheet http://openpyxl.readthedocs.org/en/latest/formatting.html

但我找不到读取现有作品中的条件格式信息的方法sheet。

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

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')

我真的很接近,但我无法留下颜色。仍然有错误,但至少以下确实添加了 keep conditional formatting rules if not the fill choice:

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)

这一个衬里实现了同样的效果(但最终结果相同):

ws.conditional_formatting.update(sh.conditional_formatting.cf_rules)

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

<repairedRecord>Repaired Records: Conditional formatting from /xl/worksheets/sheet2.xml</repairedRecord></repairedRecords>

当我尝试直接复制 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()

我一直在寻找 source code 的想法。

编辑

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