简体   繁体   中英

Python copying one work sheet to another in excel

I need to copy one excel worksheet to another. What I found so far is FillAcrossSheets to do this operation in Python. Below is my code:

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')

excel.Visible = False   #Keep the excel sheet closed
excel.DisplayAlerts = False  #"Do you want to over write it?" Will not Pop up

filepath = "C:/Pwr_Mgmt_Template.xlsx"

#Copy data from sheet named Template
sheetID = 'Template'

#Open the excel sheet
wb = excel.Workbooks.Open(filepath)

ws = wb.Worksheets(sheetID)

#Create a new sheet with name SATA-SkewData_Core1.1
ws = wb.Worksheets.Add()
ws.Name = "SATA-SkewData_Core1.1"
ws = wb.Worksheets(sheetID)

#Copy contents from Template to SATA-SkewData_Core1.1
wb.Worksheets.FillAcrossSheets(wb.Worksheets(sheetID).Range("A5:AF16"))

wb.Save()

excel.Application.Quit()

Now, if I need to create other sheets then Fill Across Sheets method will copy to these sheets too and will destroy the data. Rather than filling all across the sheets, is there a way to selectively copy from one sheet to exactly another sheet?

In standard procedure I opened two worksheets from two different workbooks. The below line copies the template worksheet (ws_temp) to the power measurement work sheet (ws_pwr). The row number can also be supplied as an argument so that the same template can be copied in the same worksheet but with a different row number:

ws_temp.Range("A5:AF16").Copy(ws_pwr.Range("A%s:AF%s" % (chart_first_row, chart_last_row)))

The row numbers copied from the template are 5 and 16 respectively.

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