使用Python刷新Excel图表外部数据链接

时间:2019-01-17 14:25:05

标签: python excel win32com

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

有人能为我提供如何完成这项工作的替代解决方案吗?

编辑

因此,我尝试了一些更简单的方法来进行测试。我在temp中创建了一个名为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()

我的代码没有错误,并且正在关注其他人在网上发布的示例。有人可以指出我该怎么做吗?

1 个答案:

答案 0 :(得分:0)

答案是我需要在更新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()