Sorry if I ask a question that may have been asked before but I could not really find the answer in Google and Stack Overflow forums.
Question is connected with openpyxl
usage as it is the most convenient library which works with xlsx
files.
import openpyxl
wb = openpyxl.load_workbook("D:/Python.xlsx")
sheet = wb.active
i = 0
sheet["A1"] = i
wb.save("D:/Python.xlsx")
However, it does not work with an opened excel file. I get an error
[Errno 13] Permission denied: 'D:/Python.xlsx'
I also found similar questions:
PermissionError [errno 13] when running openpyxl python script in Komodo
write to an open exceldocument
What can I do to solve this error and make Python work with an opened file in Excel? My current version is Python 2.7. Also, if possible, what is the solution of making the same magic in xlsm
files?
UPD:
If there is no solution for the first question (except Google Docs maybe, thanks to @Alex), is it possible to write a code which makes the following algorithm perform: 1. Close an Excel app and save 2. Do staff in python, and save the results in some destination in Excel 3. Open Excel file in Excel app?
I know how to do 2. Any thoughts on 1 and 3?
UPD2:
xlwings
really does awesome job! Just what I needed! Thanks!
I want to provide a code that worked for me (just other users can find in Google and use):
import xlwings as xl
import time
wb = xl.Workbook.active()
sheet = wb.active
iter = 10
i = 0
while True:
i += 1
if i <= iter:
xl.Range("A1").value = i
time.sleep(1)
print(i)
else:
break
wb.save()
print("Done!")
OpenPyXL operates directly on files; it has nothing to do with the Excel program, and has no control over the Excel program. As such, if the file it is trying to modify is locked by Excel, there is nothing OpenPyXL can do about that.
This question is tagged with excel-vba and that is certainly one appropriate way to control the Excel program (so you can modify data while it is open in Excel, or close Excel). If you want an interface to Excel using Python, the best package these days is xlwings.