如何让xlwing等到保存完成才关闭文件

问题描述 投票:0回答:0

我一直在使用 xlwings 在 python 中编辑一些 excel 文件,但我遇到了麻烦,因为对于一个特定的文件。完成编辑后,我传递了一个命令让 python 保存并关闭该工作簿,但它在保存完成之前关闭了文件,我使用了以下命令来修复该问题:

time.sleep(2)
,但我明白这不是很有效,也不是动态的,而且很多时候,即使这样,文件也会在保存之前关闭。我现在可以增加 sleep 命令中的秒数,但我更喜欢一些等待保存完成才能关闭的代码。

我浏览过这个网站和许多其他网站,但找不到答案,人们只提到 python 等待某些计算完成以获得一些价值的方法,但他们没有提到等待保存以关闭文件。我的代码结构如下:

import xlwings as xw
import time

app = xw.App()

excel = xw.Book("file path")
excel_sheet = excel.sheets("sheet name")

##This is just an example of changing something in the file
excel_sheet.range("A1").value = 123

excel.save()
time.sleep(2)
excel.close()
app.quit

更新: 我现在尝试使用上下文管理器,但没有成功,这是我的代码:

import xlwings as xw
import time

app = xw.App()

with xw.Book("file path") as excel: 
  excel_sheet = excel.sheets("sheet name")

  ##This is just an example of changing something in the file
  excel_sheet.range("A1").value = 123

  excel.save()

app.quit
python xlwings
© www.soinside.com 2019 - 2024. All rights reserved.