I need to open and close the same workbook in a python for
loop without necessarily saving the workbook. I tried the following in xlwings
:
import xlwings as xw
for i in range(5):
print(i)
book = xw.Book()
book.app.quit()
However this will only run for the first iteration. At the second iteration I get an error:
Traceback (most recent call last):
File "D:/TEMP/SE/python/ref.py", line 5, in <module>
book = xw.Book('tree_template.xlsx')
File "C:\Users\aboufira\AppData\Local\Continuum\miniconda3\envs\SE\lib\site-packages\xlwings\main.py", line 533, in __init__
for wb in app.books:
File "C:\Users\aboufira\AppData\Local\Continuum\miniconda3\envs\SE\lib\site-packages\xlwings\main.py", line 374, in books
return Books(impl=self.impl.books)
File "C:\Users\aboufira\AppData\Local\Continuum\miniconda3\envs\SE\lib\site-packages\xlwings\_xlwindows.py", line 397, in books
return Books(xl=self.xl.Workbooks)
File "C:\Users\aboufira\AppData\Local\Continuum\miniconda3\envs\SE\lib\site-packages\xlwings\_xlwindows.py", line 313, in xl
self._xl = get_xl_app_from_hwnd(self._hwnd)
File "C:\Users\aboufira\AppData\Local\Continuum\miniconda3\envs\SE\lib\site-packages\xlwings\_xlwindows.py", line 222, in get_xl_app_from_hwnd
ptr = accessible_object_from_window(child_hwnd)
File "C:\Users\aboufira\AppData\Local\Continuum\miniconda3\envs\SE\lib\site-packages\xlwings\_xlwindows.py", line 190, in accessible_object_from_window
res = oledll.oleacc.AccessibleObjectFromWindow(
File "_ctypes/callproc.c", line 948, in GetResult
OSError: [WinError -2147467259] Unspecified error
Why does this occur? How can I get xlwings to exit out of the application without causing any problems?
Your code was almost correct, use:
import xlwings as xw
for i in range(5):
print(i)
app = xw.App(visible=True)
book = xw.Book()
app.quit()
You can also use app = xw.App(visible=False)
if you want to open a workbook without showing it.
Use this to suffice the pop-ups
app.display_alerts=False
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.