1 | initial version |
To add a pandas dataframe to an existing excel worksheet that already contains data, you can use the "pandas ExcelWriter" module.
Here are the steps to follow:
import pandas as pd
from openpyxl import load_workbook
# set the file path
file_path = "path/to/your/excel/file.xlsx"
# load the excel workbook
book = load_workbook(file_path)
# define the sheet name where you want to add the dataframe
writer = pd.ExcelWriter(file_path, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df = pd.read_csv('path/to/your/csvfile.csv')
df.to_excel(writer, sheet_name='Sheet1', startrow=3, startcol=1)
writer.save()
Note: In this example, we are adding the dataframe to Sheet1, starting from row 3 and column 1. You can change these values as per your requirement. The key point is to load the existing workbook and pass it to the pandas ExcelWriter function.