使用xlwings和python复制工作表 [英] Copying a worksheet with xlwings and python

查看:2325
本文介绍了使用xlwings和python复制工作表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在Python中使用xlwings,但无法弄清楚如何复制工作表.我想将特定的工作表视为模板,并在进行修改之前每次都复制该工作表.

I have been using xlwings in Python, but have not been able to figure out how to copy a worksheet. I want to treat a particular worksheet as a template, and copy that worksheet each time before making modifications.

我正在使用xlwings的0.11.4版本.如果没有内置此类功能,那么我可以不使用xlwings来使用pywin32函数来实现此目的.

I am using version 0.11.4 of xlwings. If such functionality is not built in, I am okay with going outside of xlwings to use pywin32 functions in order to accomplish this.

推荐答案

在几个地方四处浏览并阅读pywin32文档后,我找到了一种复制工作表的解决方案:

After poking around in several places and reading the pywin32 documentation, I found a solution to copy the worksheet:

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提供的本机功能.由于xlwings是pywin32的包装,因此.api()调用允许访问xlwings中未记录的那些pywin32函数.

This does go outside of the native functionality provided by xlwings. Because xlwings is a wrapper around pywin32, the .api() call allows access to those pywin32 functions that are undocumented in xlwings.

还请注意,"After"命令在工作表中不起作用;它将打开一个新的工作簿并复制工作表.这不应该引起太大的问题,因为我相信可以根据需要对索引进行重新排序.

Also note that the 'After' command does not work within the worksheet; it will open a new workbook with the sheet copied. This shouldn't pose too big of an issue, as I believe the indexes can be reordered if needed.

这篇关于使用xlwings和python复制工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆