我正在使用以下代码刷新 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()
但是,文件不会刷新。事实上它看起来像下面这样:
另一方面,如果我只是使用鼠标点击在桌面上打开文件,我会按预期看到数据。
最佳答案
您是否将其作为宏运行?
对于所有连接,bg 属性中的刷新是否为 false?
要尝试的事情:
一个) 计算 ActiveWorkbook.RefreshAll 而不是 wbRefresh.RefreshAll
b) Unchecking "enable background refresh"(取消勾选禁用后台刷新)
关于win32com - Python 通过添加在具有外部连接的 excel 中刷新数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58880246/