Reputation: 28060
I want to append the contents of a panda dataframe df
to an excelsheet.
This is what I did;
df.to_excel(excel_writer="target.xlsx", sheet_name="sheet_1")
The problem with this code is that it overwrites target.xlsx
. I lost all my old data in target.xlsx
as a result. What I want the code to do is to append, not overwrite the excel sheet.
I am using python 3.7.
Upvotes: 6
Views: 5931
Reputation: 361
with pd.ExcelWriter('target.xlsx', mode='a') as writer:
df.to_excel(writer, sheet_name='sheet_1')
Source: Pandas Dataframe to Excel
Upvotes: 5
Reputation: 187
You can simply read the data stored in target.xlsx and store it in a data frame. Now, using pandas
concat()
method, you can merge the two data frames (new data frame and old data frame) and finally store them in the same excel file.
Code Snippet:
import pandas as pd
old_df = pd.read_excel('target.xlsx')
frames = [old_df, new_df]
result = pd.concat(frames)
result.to_excel("target.xlsx", sheet_name="sheet_1", index=False)
I hope it helps.
Upvotes: 2
Reputation: 16
Try this:
from openpyxl import load_workbook
writer = pandas.ExcelWriter('target.xlsx', engine='openpyxl')
writer.book = load_workbook('target.xlsx')
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df.to_excel(excel_writer=writer, sheet_name="sheet_1")
writer.save()
Upvotes: 0
Reputation: 985
If you want to append a new sheet, here's your answer.
import pandas as pd
# Open the existing excel file with all sheets
df_dict = pd.read_excel('target.xlsx',sheet_name=None)
with pd.ExcelWriter(fp) as writer:
# Save the original sheets
for sheet in df_dict:
df[sheet].to_excel(writer, sheet_name=sheet)
# If the new sheet name doesn't exist, append it
if 'sheet_1' not in df_dict:
df.to_excel(writer, sheet_name='sheet_1')
Upvotes: 4
Reputation: 423
Load 'target.xlsx' in target_df. Then
new_df = target_df.append(df)
It should work fine I guess. Then save it back as 'target.xlsx'.
Upvotes: 3
Reputation: 372
I think the easiest way to do this is:
import pandas as pd
import numpy as np
import xlsxwriter
workbook = xlsxwriter.Workbook('arrays.xlsx')
worksheet = workbook.add_worksheet() # a created excel sheet
array = pd.read_csv('array.csv')
array = array.tolist()
row = 0
for col, data in enumerate(array):
worksheet.write_column(row, col, data)
workbook.close()
Here is the xlsxwriter documentation.
Upvotes: 4