我有很多奇怪格式的文件,我正在尝试创建一个函数来删除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)
但这改变不了什么。如果细胞是空的,但是是彩色的,那么openpyxl仍然认为它们不是空的。
以下帖子:Openpyxl check for empty cell
ws.max_column和ws.max_row的问题是,它也会计算空列,从而违背了目的。“
@bhaskar是对的。当我试图得到的最大列,我得到所有的纸张,相同的值,从第一个工作表。
col = []
for sheet in wb.worksheets:
col.append(sheet.max_column)
因此,即使有不同的工作表尺寸,如果单元格具有背景颜色或任何其他格式,它也会将其视为有效的非空单元格。
有人知道怎么解决这个问题吗?
提前感谢!
发布于 2021-02-09 23:48:47
此函数从给定工作表中的所有单元格(作为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'
如果您还想检查有关如何定义和应用命名样式的信息,请在这里查看:https://openpyxl.readthedocs.io/en/stable/styles.html#cell-styles-and-named-styles
https://stackoverflow.com/questions/63992822
复制相似问题