xlwings.book 如果文件已经打开则挂起

xlwings.book hangs if file is already open

如果文件已经打开,如何关闭它?

import xlwings as xw
wb = xw.Book(folderpath + 'Metrics - auto.xlsx')

使用try:except:但需要一种方法来关闭文件以便打开它,或者找到文件并使用它?

如果它已经打开,我会收到此错误:

wb = xw.Book(folderpath + 'Metrics - auto.xlsx')
Traceback (most recent call last):

  File "<ipython-input-34-85b6fd35627b>", line 1, in <module>
    wb = xw.Book(folderpath + 'Metrics  - auto.xlsx')

  File "C:\Users\ReDimLearning\AppData\Local\Continuum\anaconda2\lib\site-packages\xlwings\main.py", line 480, in __init__
    impl = app.books.open(fullname).impl

  File "C:\Users\ReDimLearning\AppData\Local\Continuum\anaconda2\lib\site-packages\xlwings\main.py", line 2751, in open
    "Cannot open two workbooks named '%s', even if they are saved in different locations." % name

ValueError: Cannot open two workbooks named 'metrics - auto.xlsx', even if they are saved in different locations.

我没有使用 xlwings 包的经验,但是查看 source code for Book.__init__,它似乎会自动查找已经打开的工作簿的任何实例。如果只有一个,那就returns吧。如果打开了多个工作簿实例,则会引发错误。如果还没有任何打开的实例,那么它将 "connect" 到它。所以,看起来您不必担心关闭文件。

这与 documentation 一致:

The easiest way to connect to a book is offered by xw.Book: it looks for the book in all app instances and returns an error, should the same book be open in multiple instances.

但是,连接到工作簿后,如果你真的想关闭它,有一个Book.close方法:

Closes the book without saving it.

您可以使用

查看工作簿集合
import xlwings as xw
xw.books

并检查您的全名是否已打开,例如:

if myworkbook in [i.fullname for i in xw.books]:
   ...