我正在尝试删除工作簿中的一张工作表,但出现错误,我注意到我必须手动打开该文件保存它,然后正确加载。
from openpyxl import load_workbook
def delete_sheet_by_name(file_path, sheet_name):
wb = load_workbook(file_path)
if sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
wb.remove(sheet)
wb.save(file_path)
print(f"The sheet '{sheet_name}' has been deleted.")
else:
print(f"The sheet '{sheet_name}' does not exist in the workbook.")
file_path = r'E:\Projects\Python\Delete Sheet\1.xlsx'
sheet_name_to_delete = 'Evaluation Warning'
delete_sheet_by_name(file_path, sheet_name_to_delete)
File "E:\Projects\Python\Delete Sheet\pandas_solution.py", line 18, in <module>
delete_sheet_by_name(file_path, sheet_name_to_delete)
File "E:\Projects\Python\Delete Sheet\pandas_solution.py", line 5, in delete_sheet_by_name
wb = load_workbook(file_path)
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Skynet\anaconda3\Lib\site-packages\openpyxl\reader\excel.py", line 346, in load_workbook
reader.read()
File "C:\Users\Skynet\anaconda3\Lib\site-packages\openpyxl\reader\excel.py", line 301, in read
self.read_worksheets()
File "C:\Users\Skynet\anaconda3\Lib\site-packages\openpyxl\reader\excel.py", line 237, in read_worksheets
ws_parser.bind_all()
File "C:\Users\Skynet\anaconda3\Lib\site-packages\openpyxl\worksheet\_reader.py", line 465, in bind_all
self.bind_cells()
File "C:\Users\Skynet\anaconda3\Lib\site-packages\openpyxl\worksheet\_reader.py", line 368, in bind_cells
for idx, row in self.parser.parse():
File "C:\Users\Skynet\anaconda3\Lib\site-packages\openpyxl\worksheet\_reader.py", line 163, in parse
obj = prop[1].from_tree(element)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Skynet\anaconda3\Lib\site-packages\openpyxl\descriptors\serialisable.py", line 103, in from_tree
return cls(**attrib)
^^^^^^^^^^^^^
TypeError: SheetFormatProperties.__init__() got an unexpected keyword argument 'defaultColWidthPt'
我想修复 Microsoft Excle 的 Excel 文件格式
import openpyxl
import xlwings as xw
def fix_and_load_excel(file_path):
try:
app = xw.App(visible=False) # Open Excel in the background
workbook = app.books.open(file_path)
workbook.save()
workbook.close()
app.quit()
repaired_workbook = openpyxl.load_workbook(file_path)
print("Workbook repaired and loaded successfully.")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
file_path = r'E:\Projects\Python\Delete Sheet\1.xlsx'
fix_and_load_excel(file_path)
可以自动执行,但我喜欢一个代码来执行此操作。