Copying to a specific sheet: openpyxl - destination sheet ignored when using copy_worksheet

白昼怎懂夜的黑 提交于 2019-12-24 21:57:40

问题


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


来源:https://stackoverflow.com/questions/51128029/copying-to-a-specific-sheet-openpyxl-destination-sheet-ignored-when-using-cop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!