Copying to a specific sheet: openpyxl - destinatio

2019-08-26 04:42发布

问题:

Per this answer and these documents I tried to specify a source and target sheet to write to, but when I do, the results are the same as if I hadn't specified a target:

from openpyxl import load_workbook 
wb = load_workbook('MyFile.xlsx')
ws = 'Sheet1'


idx = book.index(ws)
new_ws = 'Test'
book.create_sheet(new_ws, idx+1)
source = book[ws]
target = book[new_ws]
target = book.copy_worksheet(source)
wb.save('Output.xlsx')

vs

source = book[ws]
book.copy_worksheet(source)
wb.save('Output.xlsx')

Both result in a new worksheet called Sheet1 Copy added to the end of the workbook. How to a copy a sheet into another empty sheet, or specific location within the workbook?

回答1:

# new copied sheet was assigned to target
target = wb.copy_worksheet(wb.source_sheet)

# now just change the name to desired one
target.title = desired_name