[英]Update Excel Spreadsheet with Real-Time Python Data
I'm quite new to Python and have mostly targeted learning the language exactly to automate some processes and update \/ populate excel spreadsheets with realtime data.我对 Python 还是很陌生,主要目标是学习该语言以完全自动化一些流程并使用实时数据更新\/填充 Excel 电子表格。 Is there a way (eg through openpyxl) to update specific cells with data that's extracted through python packages such as pandas or web scraping through BeautifulSoup ?有没有办法(例如通过 openpyxl)使用通过 python 包(如 pandas)或通过 BeautifulSoup 抓取的网络提取的数据来更新特定单元格?
I already have the necessary code to extract the data-series that I need for my project in Python but am stuck entirely on how to link this data to excel.我已经有了必要的代码来提取我在 Python 中的项目所需的数据系列,但我完全坚持如何将这些数据链接到 Excel。
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
start = dt.datetime(2000,1,1)
end = dt.datetime.today()
tickers = [
"PYPL",
"BABA",
"SAP"
]
df = web.DataReader (tickers, 'yahoo', start, end)
print (df.tail(365)['Adj Close'])
Pandas has a method to export a Dataframe to Excel. Pandas 有一种将 Dataframe 导出到 Excel 的方法。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html
filename = "output.xlsx"
df.to_excel(filename)
One option is to run your python script run on a schedule and output to .csv or another format that Excel can link to.一种选择是按计划运行 Python 脚本并输出为 .csv 或 Excel 可以链接到的另一种格式。 This option allows the data to be updated whenever the python script is executed.此选项允许在执行 python 脚本时更新数据。
Setup:设置:
(Appreciate that this is an old question). (感谢这是一个老问题)。 Real time data in Excel is possible with xlOil<\/a> .使用xlOil 可以获得<\/a>Excel 中的实时数据。 xlOil allows you to very easily define an Excel RTD (real time data) function in python. xlOil 允许您在 python 中非常轻松地定义 Excel RTD(实时数据)函数。 Excel's RTD functions operate outside the normal calc cycle and can push data onto a sheet. Excel 的 RTD 函数在正常计算周期之外运行,可以将数据推送到工作表上。
Your example could be written as:你的例子可以写成:
import xloil, datetime as dt, asyncio
import pandas_datareader.data as web
start = dt.datetime(2000,1,1)
@xloil.func
async def pyGetTickers(names:list, fetch_every_secs=10):
while True:
yield web.DataReader(
names, 'yahoo', start, dt.datetime.now())
await asyncio.sleep(fetch_every_secs)
One easy solution is using xlwings
library一种简单的解决方案是使用xlwings
库
import xlwings as xw
..
xw.Book(file_path).sheets['Sheet_name'].range('A1').value = df
this would print out your df
to cell A1 of an excel file, via COM - which means it actually writes the values while file is open.这将通过 COM 将您的df
打印到 Excel 文件的单元格 A1 - 这意味着它实际上是在文件打开时写入值。
Hope this is helpful希望这有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.