2

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')
Sir DrinksCoffeeALot
  • 593
  • 2
  • 11
  • 20

4 Answers4

1

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.

Falloutcoder
  • 991
  • 6
  • 19
0

I think You could use xlwings

Here You have description how to open Excel File : Opening Workbook

and then siply use API to, copy one sheet and add as new one : Sheets-Api

Take_Care_
  • 1,957
  • 1
  • 22
  • 24
0

Is there a particular need to use Python as your solution? Using Visual Basic macros seems to be a better fit here. If it needs to fit in with a Python program consider building a macro in your Excel file, then calling that file from the Python script.

CJC
  • 400
  • 4
  • 15
0

Although this question is old, but hope the comment will still be useful to update newcomers.

As mentioned by Falloutcoder, you can use the openpyxl module for the Excel task. For the data copy, you can use "for loop" and "ws2.cell(row=i,column=j).value=ws1.cell(row=i,column=j).value" functions to copy data from one sheet to another. enter link description here

Eureka JX
  • 66
  • 3