I have an excel sheet which has 150 rows of data. Now, I want to append a dataframe to that sheet without deleting or replacing the data using python.
I have tried code like this, it is deleting the existing content from the excel and writing the dataframe into it.
JavaScript
x
11
11
1
import pandas as pd
2
import openpyxl
3
4
workbook = openpyxl.load_workbook("test.xlsx")
5
writer = pd.ExcelWriter('test.xlsx', engine='openpyxl')
6
writer.book = workbook
7
writer.sheets = dict((ws.title, ws) for ws in workbook.worksheets)
8
data_df.to_excel(writer, 'Existing_sheetname')
9
writer.save()
10
writer.close()
11
And other solutions provided here but with no outcome.
Any suggestion is appreciated.
Advertisement
Answer
Firstly I created excel file with some data in range C5:I18.
JavaScript
1
30
30
1
# Required imports
2
import pandas as pd
3
from pathlib import Path
4
import numpy as np
5
6
# Path to excel file
7
xl_path = Path("C://Path//to//your//Excel_file.xlsx")
8
9
# sheet name
10
sht_name = 'test'
11
12
# columns names
13
cols = list("ABCDEFG")
14
15
# random values
16
values = np.random.randint(1000, size=(20,7))
17
# create dataframe
18
df = pd.DataFrame(data=values, columns=cols)
19
20
# since I am going to create writer object with 'openpyxl' engine all methods from
21
# openpyxl could be used
22
with pd.ExcelWriter(xl_path, mode='a', engine='openpyxl', if_sheet_exists='overlay') as writer:
23
# create new variable with sheet into which we are going to save the data
24
ws = writer.sheets[sht_name]
25
# check max row for columns of interest / in my case "C"
26
max_row_for_c = max((c.row for c in ws['C'] if c.value is not None))
27
# save data to excel starting in col C so startcol=2 since pandas counts from 0
28
# from this same reason there is no need to add 1 to max_row_from_c
29
df.to_excel(writer, sheet_name=sht_name, startcol=2, startrow= max_row_for_c, header=None, index=False)
30