win32com - Python 通过添加在具有外部连接的 excel 中刷新数据不起作用

标签 win32com python-3.8

我正在使用以下代码刷新 excel 文件中的数据,该文件使用外部加载项接收数据。

import sys, os, pandas as pd, numpy as np, time, win32com.client
import win32com.client as w3c

if __name__ == '__main__':
    your_file_path = r'C:\Book11.xlsx'
    for ii in np.arange(1, 10):
        xlapp = w3c.gencache.EnsureDispatch('Excel.Application')
        xlapp.Visible = 0
        xlwb = xlapp.Workbooks.Open(your_file_path, False, True, None)
        books = w3c.Dispatch(xlwb)

        xlwb.RefreshAll()  # Runs with no errors, but doesn't refresh
        xlapp.DisplayAlerts = False
        xlwb.Save()
        xlapp.Quit()

        df = pd.read_excel(your_file_path)  # updates should be applied
        print(df)
        time.sleep(20)

# Another version of code that I tried is following:
# xlapp = win32com.client.DispatchEx("Excel.Application")
# xlapp.Visible = True
# wb = xlapp.Workbooks.Open(your_file_path)
# wb.RefreshAll()
# xlapp.CalculateUntilAsyncQueriesDone()
# xlapp.DisplayAlerts = False
# wb.Save()
# xlapp.Quit()

但是,文件不会刷新。事实上它看起来像下面这样:

enter image description here

另一方面,如果我只是使用鼠标点击在桌面上打开文件,我会按预期看到数据。

enter image description here

最佳答案

  1. 您是否将其作为宏运行?

  2. 对于所有连接,bg 属性中的刷新是否为 false?

要尝试的事情:

一个) 计算 ActiveWorkbook.RefreshAll 而不是 wbRefresh.RefreshAll

b) Unchecking "enable background refresh"(取消勾选禁用后台刷新)

关于win32com - Python 通过添加在具有外部连接的 excel 中刷新数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58880246/

相关文章:

Python:致命:不是 git 存储库停止在文件系统边界(未设置 GIT_DISCOVERY_ACROSS_FILESYSTEM)

python-pptx ".ppt"处理变通

Python:刷新工作表中的数据透视表

python - 使用 python 访问 Outlook 文件夹

python-3.x - 使用 win32com 从 xls 转换为 xlsx 时出错。如果我使用其他 excel 表,此程序会引发错误

python-3.x - python : Paste Excel cells with win32com to Powerpoint without losing cell formats

python-3.x - 如何安装 pmdarima?

Pandas read_html 无法读取表格

python - 如何在pygame中显示由点组成的圆圈?

使用nohup时python脚本无法工作