Openpyxl - 删除 Excel 文件中所有工作表的格式

Rac*_*_17 2 python excel openpyxl

我的文件有很多奇怪的格式,我正在尝试创建一个函数来删除 xlsx 文件中的任何格式。

这里的一些人建议使用“cell.fill = PatternFill(fill_type=None)”来清除给定单元格中的任何格式。

path = r'C:\Desktop\Python\Openpyxl\Formatted.xlsx
wb = xl.load_workbook(filename = path)

def removeFormatting(file):
    ws = wb[file]
    
    for row in ws.iter_rows():
        for cell in row:
            if cell.value is None:
                cell.fill = PatternFill(fill_type=None)

    wb.save(path)

for s in wb.sheetnames:
    removeFormatting(s)
Run Code Online (Sandbox Code Playgroud)

但这不会改变任何事情。如果单元格为空但有颜色,则 openpyxl 仍将它们视为非空。

在这篇文章之后: Openpyxl 检查空单元格

ws.max_column 和 ws.max_row 的问题在于它也会计算空白列,从而达不到目的。”

@bhaskar 是对的。当我尝试获取最大列时,我为所有工作表获取与第一张工作表相同的值。

col = []    
for sheet in wb.worksheets:
        col.append(sheet.max_column)
Run Code Online (Sandbox Code Playgroud)

因此,即使存在不同的工作表尺寸,如果单元格具有背景颜色或任何其他格式,它也会将其视为有效的非空单元格。

有谁知道如何解决这个问题?

提前致谢!

abu*_*abu 7

此函数从给定工作表中的所有单元格中删除样式(作为ws对象传递)。因此,您可以打开文件,迭代所有工作表并将此函数应用于每个工作表:

def removeFormatting(ws):
    # ws is not the worksheet name, but the worksheet object
    for row in ws.iter_rows():
        for cell in row:
            cell.style = 'Normal'
Run Code Online (Sandbox Code Playgroud)

如果您还想检查有关如何定义和应用命名样式的信息,请查看此处: https ://openpyxl.readthedocs.io/en/stable/styles.html#cell-styles-and-named-styles