Reputation: 13788
I know how to write multiple dataframes to different sheets in one excel.
But now I want to write two different dataframes in one excel horizonally.
For example:
The only way I know is
pd.concat((df1.reset_index() , df2.reset_index(), axis=1).to_excel('1.xlsx')
But this is not convenient.
Reason:
PS: it is just inconvenient
to use pd.concat
, because need much effort to make that excel look beautiful.
I also tried to use pd.ExcelWriter
which can assign startcol
:
job 1:
file_name = 'xxx.xlsx'
writer = pd.ExcelWriter(file_name, engine='xlsxwriter',
datetime_format='yyyy-mm-dd',
date_format='yyyy-mm-dd')
df1.to_excel(writer, sheet_name=sheet_name, startrow=0 , startcol=0)
job 2
file_name = 'xxx.xlsx'
writer = pd.ExcelWriter(file_name, engine='xlsxwriter',
datetime_format='yyyy-mm-dd',
date_format='yyyy-mm-dd')
df2.to_excel(writer, sheet_name=sheet_name, startrow=0 , startcol=df1.shape[1]+2)
But this overwrite the excel ....
I hope there is a easy way to write a dataframe in position startrow, startcol
without overwirting the file ?
Upvotes: 1
Views: 2183
Reputation: 1933
You can use xlwings: Get the last column of df1 then go two columns further right with .offset(column_offset=2)
and then insert df2. It's flexible and easy to use (no need to use pd.concat
):
import xlwings as xw
import pandas as pd
df1 = pd._testing.makeDataFrame()
df2 = pd._testing.makeDataFrame()
with xw.App(visible=False) as app:
wb = xw.Book()
wb.sheets[0].range("A1").value = df1
wb.sheets[0].range("A1").expand("right")[-1].offset(column_offset=2).value = df2
wb.save()
wb.close()
Upvotes: 0
Reputation: 61
Create columns in df1 and df2 with values as row numbers. This way you will retain the order of the two dataframes.
2) Merge the two dataframes on the the columns created in step one
3) Push this to excel
df1['key']= df1.reset_index().index
df2['key'] = df2.reset_index().index
pd.merge(df1, df2, how='outer',on='key').to_excel('1.xlsx')
Upvotes: 1