I have a template excel file named as template.xlsx
which has a number of sheets. I would like to copy data from a seperate .csv
file into the first sheet of template.xlsx
(named as data
) and save the new file as result.xlsx
while retaining the original template file.
I want to paste the data starting from the second row in the data
sheet of template.xlsx
This is the code I have developed so far
import pandas as pd
from openpyxl.utils.dataframe import dataframe_to_rows
import openpyxl
from shutil import copyfile
template_file = 'template.xlsx' # Has a header in row 1 already which needs to be skipped while pasting data but it should be there in the output file
output_file = 'result.xlsx'
copyfile(template_file, output_file)
df = pd.read_csv('input_file.csv') #The file which is to be pasted in the template
wb = openpyxl.load_workbook(output_file)
ws = wb.get_sheet_by_name('data') #Getting the sheet named as 'data'
for r in dataframe_to_rows(df, index=False, header=False):
ws.append(r)
wb.save(output_file)
I am not able to get the desired output
The template file (with an extra row) on the left and the input file (data to be copied to the template) on the right, look like this