简体   繁体   中英

multiple dataframes from pandas to one excel sheet without deleting other sheets with python

i have 2 dfs which i want to export to an existing excel file which already has three sheets. The two dfs should be in sheet "Sheet1" (a new sheet)

df = pd.read_excel("Data Set Finished.xlsx", sheet_name="Details")
df2 = df.sum(axis=1)

writer = pd.ExcelWriter('Data Set Finished.xlsx', engine='openpyxl', mode ="a")


df.to_excel(writer, sheet_name='Sheet1', index=False) 
df2.to_excel(writer, sheet_name='Sheet1', startrow= 1,startcol=12, index=False, header=False)

But i get this error: Sheet 'Sheet1' already exists and if_sheet_exists is set to 'error'. i tried xlsxwriter instead of openpyxl but that just deletes the other sheets and apparently xlsxwriter doesnt have the append mode. How can i fix this?

I am a huge fan of xlwings which is part of the anaconda distribution. This allows you to interactively interact with EXCEL which is really handy for viewing dataframes ( eg xl.view(df) ). It will also allow you to position output exactly where you want it, and you could format cells (eg make titles bold and a different colour) should you want.

You could try something like this, where file should reference the existing workbook (including file path). Here I have assumed Sheet1 already exists in the excel workbook. If that is not the case, then add a sheet via wb.sheets.add() .

import numpy as np
import pandas as pd
import xlwings as xl

df1 = pd.DataFrame({
    'date':pd.date_range(start='1/1/1990', periods=10, freq='Q'),
    'a': np.random.choice(range(100),10),
    'b': np.random.choice(range(100),10),
})

df2 = pd.DataFrame({
    'date':pd.date_range(start='1/1/2000', periods=10, freq='Q'),
    'c': np.random.choice(range(100),10),
    'd': np.random.choice(range(100),10),
})

df3 = pd.DataFrame({
    'date':pd.date_range(start='1/1/2010', periods=10, freq='Q'),
    'e': np.random.choice(range(100),10),
    'f': np.random.choice(range(100),10),
})


file = 'C:/Users/BRB/Book1.xlsx'

wb = xl.Book(file)
ws = wb.sheets('Sheet1')

ws.range('A1').value = df1
ws.range('E1').value = df2
ws.range('A14').value = df3

wb.save()
wb.close()

And if you want to suppress the index, just include the option options(index=False) as follows:

ws.range('A1').options(index=False).value = df1
ws.range('E1').options(index=False).value = df2
ws.range('A14').options(index=False).value = df3

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