我在openpyxl中无法保存正在使用的活动文件。
wb_obj = load_workbook(filename="C:\\Users\\timde\PycharmProjects\\starshipit\\test.xlsx", read_only=False)
sheet_obj = wb_obj.active
sheet_obj.cell(row=2, column=10).value = 500
wb_obj.save("test.xlsx")
我又收到此错误
File "C:/Users/timde/PycharmProjects/starshipit/writeback_to_sheet.py", line 22, in <module>
write_back()
File "C:/Users/timde/PycharmProjects/starshipit/writeback_to_sheet.py", line 15, in write_back
wb_obj.save("test.xlsx")
File "C:\Users\timde\PycharmProjects\starshipit\venv\lib\site-packages\openpyxl\workbook\workbook.py", line 392, in save
save_workbook(self, filename)
File "C:\Users\timde\PycharmProjects\starshipit\venv\lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook
archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
File "C:\Users\timde\AppData\Local\Programs\Python\Python38-32\lib\zipfile.py", line 1251, in __init__
self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'test.xlsx'
但是如果我将文件名更改为test1.xlsx,它将创建一个新文件并为我保存。
所以问题只是将我当前所在的工作簿保存为本身
谢谢大家。非常感谢
MS Office应用程序通常对打开的文件进行写锁定。由于您已在Excel中打开工作簿,因此Python将无法打开同一工作簿。这表现为您所看到的PermissionError
。一种简单的解决方案是在您要在其他地方使用Excel时关闭文件。