0

使用最新版本运行 xlwings 0.26.1(Anaconda 3.83 的最新版本)或 0.10.0(出于兼容性原因使用)时,Office 365 Excel在运行时移动工作表后出现错误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 抛出一个错误,我必须单击该错误才能继续该过程。

4

2 回答 2

0

我发现适用于两者的解决方案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()命令是在 version中引入0.9.0的。只要您先关闭工作簿,我看不出它会如何导致数据丢失或损坏的任何问题。

于 2022-02-04T20:21:12.390 回答
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()
于 2022-02-06T13:26:02.180 回答