首页 > 解决方案 > 使用 Python 刷新 Excel 图表外部数据链接

问题描述

我正在尝试使用 python 更新 Excel 中图表的外部数据链接。图表位于其中,workbook1.xlsm它引用以更新自身的数据位于external_workbook.xlsx. 分离的原因是数据必须workbook1.xlsm使用 python 定期更新,如果图表在workbook1.xlsm.

我已经查看了各种解决方案,但到目前为止没有一个对我有用。到目前为止,我尝试过的两种解决方案包括 (1) 以编程方式刷新工作簿和 (2) 在工作簿中运行宏以以编程方式刷新它。

(1) 的代码:

import win32com.client as w3c
xlapp = w3c.gencache.EnsureDispatch('Excel.Application')
xlapp.Visible = 0
xlwb = xlapp.Workbooks.Open(r'{}\{}'.format(path, fname), False, True, None)
xlwb.RefreshAll() # Runs with no errors, but doesn't refresh
time.sleep(5)
xlwb.Save()
xlapp.Quit()

(2) 的代码:

# ***************** #
# Excel macro - I've verified the macro works when I have the worksheet open.
Sub Update_Links()
    ActiveWorkbook.UpdateLink Name:=ActiveWorkbook.LinkSources
End Sub
# ***************** #

import win32com.client as w3c
xlapp = w3c.gencache.EnsureDispatch('Excel.Application')
xlapp.Visible = 0
xlwb = xlapp.Workbooks.Open(r'{}\{}'.format(path, fname), False, True, None)
xlwb.Application.Run("{}!Module1.Update_Links".format(fname)) # Runs with no errors, but doesn't refresh
xlwb.Save()
xlapp.Quit()

我在 Excel 中的图表系列是

# External data link for Excel chart #
=SERIES(,'...path_to_external_file...[external_workbook.xlsx]Sheet1'!$A$2:$A$2000,
'...path_to_external_file...[external_workbook.xlsx]Sheet1'!$F$2:$F$2000,1)

谁能为我提供如何使这项工作的替代解决方案?

编辑

所以我尝试了一些更简单的方法来测试它。我创建了一个名为tempin的新工作表,workbook1.xlsm并尝试使用下面的代码将随机值写入单元格 A1。运行代码后临时表仍然是空白的。

import win32com.client as w3c
import random

xlapp = w3c.gencache.EnsureDispatch('Excel.Application')
xlapp.Visible = 0
xlwb = xlapp.Workbooks.Open(r'{}\{}'.format(path, fname), False, True, None)
books = w3c.Dispatch(xlwb) 

sheet_temp = books.Sheets('temp')
sheet_temp.Cells(1,1).Value = random.random()

xlwb.RefreshAll() # Runs with no errors, but doesn't refresh
time.sleep(5)
xlwb.Save()
xlapp.Quit()

我的代码没有错误,并且正在关注其他人在线发布的示例。有人可以指出我在哪里出错了吗?

标签: pythonexcelwin32com

解决方案


答案是我需要external_workbook.xlsx在更新之前打开工作簿workbook1.xlsm,以便刷新数据。

工作代码如下:

import win32com.client as w3c
import random

xlapp = w3c.gencache.EnsureDispatch('Excel.Application')
xlapp.Visible = 0

# ********************************* #
# New line that fixes it #
xlwb_data = xlapp.Workbooks.Open(r'{}\{}'.format(path, 'external_workbook.xlsx'), False, True, None)
# ********************************* #

xlwb = xlapp.Workbooks.Open(r'{}\{}'.format(path, 'workbook1.xlsm'), False, True, None)
books = w3c.Dispatch(xlwb) 

sheet_temp = books.Sheets('temp')
sheet_temp.Cells(1,1).Value = random.random()

xlwb.RefreshAll() # Runs with no errors, but doesn't refresh
time.sleep(5)
xlwb.Save()
xlapp.Quit()

推荐阅读