简体   繁体   中英

Cant save excel spread sheet in openpyxl - Python

I can't save the active file I'm working in when I'm in 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")

I get this error back

 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'

But if I change the file name to test1.xlsx It creates a new file and saves it for me.

So the issue is only saving the current workbook I am in as itself

Thank you all in advance. Much appreciated

MS Office applications generally write-lock the files that they open. Since you have your workbook open in Excel, Python will not be able to open the same workbook. This manifests itself as the PermissionError that you are seeing. The simple solution is to close the file in Excel when you want to use it elsewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM