如何使用openpyxl删除包含字符串的列


wb = load_workbook('test.xlsx')
ws = wb.active
x = 0
for sheet in ws:
for cell in sheet[0:]:
if 'Attribute' in cell.value:
x = x + 1
print(x)
ws.delete_cols(x)
else:
x = x + 1
wb.save('new_test.xlsx')

我收到以下错误文件";d: \Temp\Python\Excel_Test.py";,第33行,inif cell.value中的"Attribute":TypeError:"NoneType"类型的参数不可迭代

可能不是最佳解决方案,但它有效:

import openpyxl

wb = openpyxl.load_workbook('file_name.xlsx')
ws = wb.active
x = ws.max_row
y = ws.max_column
print(f"maxrow: {x}, maxcol: {y}")
for row in range(2, x+1):
for col in range(1, y+1):
#print(ws.cell(row=row, column=col).value)
if 'Attribute' in str(ws.cell(row=row, column=col).value):
ws.delete_cols(col)
wb.save('file_name.xlsx')

相关内容

最新更新