当使用最新版本的Office 365 Excel
运行xlwings 0.26.1(Anaconda 3.83的最新版本(或0.10.0(出于兼容性原因使用(时,在运行app.quit()
:时移动工作表后出现错误
import xlwings as xw
import pythoncom
pythoncom.CoInitialize()
app = xw.apps.add()
app.display_alerts = False
app.screen_updating = False
wbSource = app.books.open('pathSourceTemp')
wsSource = wbSource.sheets['sourceSheet']
wbDestination = app.books.open('pathDestinationTemp')
wsDestination = None
#Grabs first sheet in destination
wsDestination = wbDestination.sheets[0]
#Copy sheet "before" destination sheet (which should be 1 sheet after the destination sheet)
wsSource.api.Copy(Before=wsDestination.api)
wbDestination.save()
#Close workbooks and app
wbDestination.close()
wbSource.close()
app.screen_updating = True
app.quit()
最后一行导致Excel抛出一个错误,我必须单击它才能继续处理。
我发现的同时适用于xlwings 0.10.0
和0.26.1
的解决方案是使用app.kill()
方法进行简单的暴力:
#Close workbooks and app
wbDestination.close()
wbSource.close()
app.screen_updating = True
#app.quit() <- throws error
app.kill() <- no error
不确定这可能会产生什么意外的副作用,但显然.kill()
命令是在0.9.0
版本中引入的。只要你先关闭工作簿,我看不出它会导致任何数据丢失或损坏的问题。
自版本0.24.3以来,惯用方法是使用with xw.App() as app
。这样做的好处是,如果使用隐藏实例(visible=False
(而代码失败,那么后台就不会留下任何隐藏的excel进程。
import xlwings as xw
# You could also omit .screen_updating (and .display_alerts)
# and use xw.App(visible=False) instead, if appropriate.
with xw.App() as app:
app.display_alerts = False
app.screen_updating = False
wbSource = xw.Book()
wbDestination = xw.Book()
# Do your stuff here.
app.screen_updating = True
# Save as needed, for example: wbDestination.save()
wbSource.close()
wbDestination.close()