OpenPyxl Copy a range of rows x times

Viewed 27

I have an excel sheet with 400+ columns and 48 rows long. I want openpyxl to copy this with the exact same values another x times.

Most likely it will be like x=4, so 4x 48 rows.

I can't seem to find a solution that does this. I could do it with looping but it would take so much running time.

Is there no option to copy a range of rows and paste it at end of the excel file?

1 Answers

The esiest way is probably to use Pandas.
You can create a dataframe of the Excel sheet and then just paste that X times back to Excel.
The following code is an example. It does not include any row Header in the original however if this exists and is required you can dump the first time with a header.

import pandas as pd

in_filename = 'Original.xlsx'
in_sheet = 'Sheet1'
out_filename = 'NewBook.xlsx'
save_sheet = 'NewSheet'
number_duplicates = 3

# Create dataframe from the original 
df = pd.read_excel(in_filename, sheet_name=in_sheet)

# Create writer to write df to Excel workbook
writer = pd.ExcelWriter(out_filename, engine='openpyxl')
for i in range(number_duplicates): 
    # Write dataframe without header row or index column
    df.to_excel(writer, sheet_name=save_sheet,
                index=False,
                header=False,
                startrow=i*len(df.index),
                startcol=0)

writer.save()
Related