使用Python刷新Excel外部数据

时间:2016-11-30 16:50:46

标签: python excel pandas

我有一个Excel文件,我在其上运行Python脚本。 Excel文件具有外部数据连接,需要在运行Python脚本之前刷新。我所指的功能在这里:

Refresh External Data

我正在使用Python 2.7并且依赖Pandas进行大多数Excel数据解析。

5 个答案:

答案 0 :(得分:7)

如果您使用的是Windows,并且我相信您已获得屏幕截图,则可以使用win32com模块。它将允许您 - 从python - 打开Excel,加载工作簿,刷新所有数据连接,然后退出。语法最终非常接近VBA。

我建议你通过pip(pypiwin32)安装pip install pypiwin32

import win32com.client

# Start an instance of Excel
xlapp = win32com.client.DispatchEx("Excel.Application")

# Open the workbook in said instance of Excel
wb = xlapp.workbooks.open(<path_to_excel_workbook>)

# Optional, e.g. if you want to debug
# xlapp.Visible = True

# Refresh all data connections.
wb.RefreshAll()
wb.Save()

# Quit
xlapp.Quit()

答案 1 :(得分:2)

一个小笔记,但很重要。上面的所有代码都是正确的,但是由于只保存文件而不关闭文件,因此会出现Err 13权限问题。

保存后

添加 wb.Close(),否则打开的Excel将保留在后台应用程序中,如果您使用其中的500个,可能会遇到麻烦

答案 2 :(得分:1)

将其添加为答案,因为这是第一个Google链接-第一个答案中的代码有效,但大小写不正确,应该为:

import win32com.client
import time

xlapp = win32com.client.DispatchEx("Excel.Application")
wb = xlapp.Workbooks.Open(<path_to_excel_workbook>)
wb.RefreshAll()
time.sleep(5)
wb.Save()
xlapp.Quit()

答案 3 :(得分:1)

CalculateUntilAsyncQueriesDone()将保留程序,并等待刷新完成。

xlapp = win32com.client.DispatchEx("Excel.Application")
wb = xlapp.Workbooks.Open(<path_to_excel_workbook>)
wb.RefreshAll()
xlapp.CalculateUntilAsyncQueriesDone()
wb.Save()
xlapp.Quit()

答案 4 :(得分:1)

除了其他人说的话之外,当代码到达Quit行时,我再次保持保存对话框。我将DisplayAlerts标志设置为false,它解决了我的问题。我也不需要睡眠定时器。这对我有用:

import pyodbc

ex_value = "SELECT * FROM OPENQUERY(LinkedServerName,'SELECT * FROM LinkedServerName.SomeTable')"
# I have to connect to some local database on the server and cannot connect to linked server initially.
odbc_driver, server, db = '{ODBC Driver 17 for SQL Server}', 'MyServerName', 'LocalDatabase'

with pyodbc.connect(driver=odbc_driver, host=server, database=db, trusted_connection='yes') as conn:
    conn.autocommit = False
    cursor = conn.cursor()
    cursor.execute(ex_value)
    tables = cursor.fetchall()

    for row in tables:
        print('Row: {}'.format(row))

    cursor.close()