Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XlsxWriter python to write a dataframe in a specific cell

One can write data to a specific cell, using:

xlsworksheet.write('B5', 'Hello')

But if you try to write a whole dataframe, df2, starting in cell 'B5':

xlsworksheet.write('B5', df2)

TypeError: Unsupported type <class 'pandas.core.frame.DataFrame'> in write()

What should be the way to write a whole dataframe starting in a specific cell?

The reason I ask this is because I need to paste 2 different pandas dataframes in the same sheet in excel.

like image 432
Gabriel Avatar asked Sep 04 '26 17:09

Gabriel


1 Answers

XlsxWriter doesn't write Pandas dataframes directly. However, it is integrated with Pandas so you can do it the other way around.

Here is a small example of writing 2 dataframes to the same worksheet using the startrow parameter of Pandas to_excel:

import pandas as pd

df1 = pd.DataFrame({'Data': [10, 20, 30, 40]})
df2 = pd.DataFrame({'Data': [13, 24, 35, 46]})

writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

df1.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet1', startrow=6)

Output:

enter image description here

You can turn off the column and row indexes using other to_excel options.

like image 181
jmcnamara Avatar answered Sep 07 '26 06:09

jmcnamara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!