I have following code and trying to write a data frame into an "Existing" worksheet of an Excel file (referred here as test.xlsx). Sheet3 is the targeted sheet, where I want to place the data and I don't want to replace the entire sheet with a new one.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
book = load_workbook('test.xlsx')
writer = pd.ExcelWriter('test.xlsx')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets) # *I am not sure what is happening in this line*
df.to_excel(writer,"Sheet3",startcol=0, startrow=20)
When I am running the code line by line, I am getting this error for the last line:
AttributeError: 'Workbook' object has no attribute 'add_worksheet'. Now why am I seeing this error when I am not trying to add worksheet ?
Note: I am aware of this similar issue Python How to use ExcelWriter to write into an existing worksheet but its not working for me and I can't comment on that post either.
openpyxl has support for Pandas dataframes so you're best off using it directly. See http://openpyxl.readthedocs.io/en/latest/pandas.html for more details.
Here is a helper function:
Usage:
Some details:
**to_excel_kwargs
- used in order to pass additional named parameters todf.to_excel()
like i did in the example above - parameterstartcol
is unknown toappend_df_to_excel()
so it will be treated as a part of**to_excel_kwargs
parameter (dictionary).writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
is used in order to copy existing sheets towriter
openpyxl object. I can't explain why it's not done automatically when readingwriter = pd.ExcelWriter(filename, engine='openpyxl')
- you should ask authors ofopenpyxl
module about that...You can use
openpyxl
as the engine when you are creating an instance ofpd.ExcelWriter
.Hope this works for you.