I am new to Python and working on a project that I could use some help on. So I am trying to modify an existing excel workbook in order to compare stock data. Luckily, there was a program online that retrieved all the data I need and I have successful been able to pull the data and write the data into a new excel file. However, the goal is to pull the data and put it into an existing excel file. Furthermore, I need to overwrite the cell values in the existing file. I believe xlwings is able to do this and I think my code is on the right track, but I ran into an unexpected error. The error I get is:
TypeError: Objects of type 'Period' can not be converted to a COM VARIANT (but obtaining the buffer() of this object could)
I was wondering if anyone knew why this error came up? Also, does anyone know how to fix it? Is it fixable? Is my code wrong? Any help or guidance is appreciated. Thank you.
import good_morning as gm
import pandas as pd
import xlwings as xw
#import income statement, balance sheet, and cash flow of AAPL
fd = gm.FinancialsDownloader()
fd_frames = fd.download('AAPL')
#Creates a DataFrame for only the balance sheet
df1 = pd.DataFrame(list(fd_frames.values())[0])
#connects to workbook I want to modify
wb = xw.Book(r'C:\Users\vince\Project\Spreadsheet.xlsm')
#sheet I would like to modify
sht = wb.sheets[1]
#modifies & overwrites values in my spreadsheet(this is where I get the type_error)
sht.range('M6').value = df1
Data Types:
type(fd_frames)
>>> <class 'dict'>
fd_frames.values())[0].info()
>>> <class 'pandas.core.frame.DataFrame'>
RangeIndex: 22 entries, 0 to 21
Data columns (total 8 columns):
parent_index 22 non-null int64
title 22 non-null object
2012 19 non-null float64
2013 20 non-null float64
2014 20 non-null float64
2015 20 non-null float64
2016 20 non-null float64
2017 20 non-null float64
dtypes: float64(6), int64(1), object(1)
memory usage: 1.5+ KB
Selecting from a Dict using
list(fd_frames.values())[0]
does lead to unpredictable Results. Show the Keys of the Dict and choose the one you interested off using these Key, e.g.:Beside this, neither of the Dimension in your
pandas.DataFrame
does matchM6:M30
= 25. There are only 8 columns with 20 Values. Therfore you have to align your Worksheet Range to 20 Rows. To write Column 2017 to the Worksheet, e.g.:Update a Workbooks Worksheet Range with List Values.
Using: OpenPyXL: A Python library to read/write Excel 2010 xlsx/xlsm files
Tested with Python:3.4.2 - openpyxl:2.4.1 - LibreOffice:4.3.3.2
Here's how I do a similar procedure for other Stack explorers: