使用xlwings和python复制工作表的解决scheme

我一直在python中使用xlwings,并努力寻找合适的代码来复制工作表(如模板)。 在几处地方探索并阅读pywin32文档后,我find了一个解决scheme来复制工作表。 我想在这里发布,以帮助其他人search相同的问题,以节省一些时间。 这从xlwings的版本0.11.4开始工作。

import xlwings as xw wb = xw.Book('filename.xlsx') sheet = wb.sheets['Sheet1'] #copy within the same sheet sheet.api.Copy(Before=sheet.api) #copy to a new workbook sheet.api.Copy() #copy a third time at the beginning of the sheets sheet2 = wb.sheets['sheet1 (2)'] sheet.api.Copy(Before=sheet2.api) #copy to an existing workbook by putting it in front of a worksheet object sheet.api.Copy(before=existingSheet.api) 

这一切都是因为xlwings是pywin32的包装,而.api调用允许访问那些在xlwings中没有logging的pywin32函数。 另请注意,“After”命令在工作表中不起作用,它将打开一张复制工作表的新工作簿。 这不应该造成太大的问题,因为我相信如果需要,索引可以重新sorting。 谢谢。