使用python刷新Excel外部数据连接

时间:2016-07-20 21:04:26

标签: python excel

我有一个带有外部数据连接的excel文件。我需要使用python刷新连接数据。

我尝试了灵魂

import win32com.client
import os
fileName="testconn.xlsx"
xl = win32com.client.DispatchEx("Excel.Application")
wb = xl.workbooks.open(fileName)
xl.Visible = True
wb.RefreshAll()
wb.Save()
xl.Quit()

但是这个解决方案需要在机器上安装excel。

我认为的另一种方法是: - 如果我得到数据连接的URL和加载它们的命名范围的映射,我可以从URL下载数据并使用openpyxl更新命名范围内的数据。

有更好的方法吗?是否有任何python库具有检索连接和刷新连接的功能?

提前致谢:)

1 个答案:

答案 0 :(得分:0)

绝对刷新Excel工作表需要安装Excel。所以你的方法看起来很好,尽管可能有更简单的方法。 Pandas有一个很好的库来操作Excel电子表格pandas.read_excelpandas.DataFrame.to_excel函数http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html但是单独使用Pandas无法写入命名范围,它会让您指定工作表并至少启动单元格(如果您的命名范围不能更改起始单元格/工作表,则很好)。但是你可以添加另一个包并将其与Pandas(或它自己)一起使用来写入命名范围 - xlsxwriter见这里: http://xlsxwriter.readthedocs.io/example_defined_name.html#ex-defined-name https://xlsxwriter.readthedocs.io/working_with_pandas.html

import xlsxwriter
workbook = xlsxwriter.Workbook('defined_range.xlsx')
worksheet.write('defined_range', data) # writes to defined_range in the Excel workbook 

Pandas还允许您直接从URL中读取数据,这有助于您提出的解决方案pandas.read_htmlhttp://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html

相关问题