Sir DrinksCoffeeALot Sir DrinksCoffeeALot - 15 days ago 8
Python Question

How to copy and paste existing sheet in existing workbook using python?

I've been searching for a way to do the following:


  1. Open an existing workbook that contains several worksheets,
    .xlsl
    .

  2. Create a new worksheet, and rename it.

  3. Copy data and formatting from an existing worksheet, named 'Template', and paste that data to the previously created worksheet.



Is there any way to do what I need?

EDIT:
This is the way how to do it:

import openpyxl
from openpyxl.worksheet.copier import WorksheetCopy

workbook = openpyxl.load_workbook('input.xlsx')
template_worksheet = workbook.get_sheet_by_name(sheet_name)
new_worksheet = workbook.create_sheet('New_Sheet_Name')
instance = WorksheetCopy(template_worksheet, new_worksheet)
WorksheetCopy.copy_worksheet(instance)
workbook.save('output.xlsx')

Answer

You will have to use python package for this task, I recommend you use openpyxl package. Basic usage of the package can be found here.

https://openpyxl.readthedocs.io/en/default/usage.html

You will basically read the excel and at the same time write a new excel, copying data row by row.