【发布时间】:2019-01-17 14:25:05
【问题描述】:
我正在尝试使用 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)
任何人都可以为我提供如何完成这项工作的替代解决方案吗?
编辑
所以我尝试了一些更简单的方法来测试它。我在workbook1.xlsm 中创建了一个名为temp 的新工作表,并尝试使用下面的代码将随机值写入单元格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()
我的代码没有任何错误,并且正在关注其他人在线发布的示例。有人能指出我哪里出了问题吗?
【问题讨论】: