python xlwings word模板_使用xlwings和python复制工作表

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.

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.

解决方案

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)

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.

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值