简体   繁体   中英

Extract the data and modify an existing excel with openpyxl

I would like to modify an existing excel via openpyxl. The purpose is to take finance data and insert it in the specific columns so that it can perform the calculations.

I would like column 1 to show the opening prices

I write this code.

 import datetime as dt import pandas as pd import pandas_datareader.data as web from openpyxl import load_workbook start = dt.datetime(2018, 1, 1) end = dt.datetime(2019, 1, 1) ticker = "AAPL" yahoo = web.DataReader(ticker, 'yahoo', start, end) #print(yahoo['Open']) wb = load_workbook('aa.xlsx') ws = wb.active ws.title = "Change Sheet__" ws["A"].value(aaa) wb.save("aa.xlsx")

The error is:

Traceback (most recent call last): File "C:\Users\Davide\Desktop\aa.py", line 23, in ws["A"].value(aaa) AttributeError: 'tuple' object has no attribute 'value'

If I add this

 n=1 for n in range(1, 100): ws.cell(row=n, column=1).value(4) n+1

It paste all 4 in column A

But I want the whole yahoo ['Open'] array to be pasted

IIUC, this should work:

from openpyxl import load_workbook
wb = load_workbook('aa.xlsx')
ws = wb['Sheet1'] # choose your sheet.

then we decide your column to replace with your df.

col_to_replace = 'A'
for index, row in df.iterrows():
    cell = f'{col_to_replace}{index+2}'
    ws[cell] = row[0]

wb.save('aa.xlsx')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM