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

标签 python excel openpyxl

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

xl = openpyxl.load_workbook(filename)

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

我可以在以下位置找到许多向电子表格添加条件格式的方法 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')

最佳答案

我真的很接近,但我无法留下颜色。仍然有错误,但至少以下确实添加了 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,规则就在那里,但是当你打开文件时,它需要自动修复,我失去了颜色。这是 super 有用的日志(此处是讽刺):

<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的想法。

编辑

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

关于python - 阅读工作表并保留条件格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28776333/

相关文章:

excel - Powershell 2.0 写回 xlsx

python - 在 openpyxl 中比较两个电子表格中的一列

python - openpyxl reader 返回 None 值

python - 具有负功率的 PyTorch 度数会产生错误吗?

python - 从python中的Parent类继承pandas dataframe的属性

excel - 为什么 vba 将 SN-Sh 替换为 Word 快照中的零为 00ap00ot?

c# - LINQ 和 ExcelQueryFactory

python - 如何在Python中测试单元格坐标以更改数据?

python - 将二进制数转换为包含每个二进制数的数组

python - 是否可以使用 python beautifulsoup 更改 html 元素的父级