简体   繁体   中英

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')

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM