Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a worksheet with xlwings and 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.

like image 506
P. Nokes Avatar asked Aug 29 '17 21:08

P. Nokes


People also ask

How do I import Xlwings into Python?

Call Python from Excel To make this run, just import the VBA module xlwings. bas in the VBA editor (Open the VBA editor with Alt-F11, then go to File > Import File... and import the xlwings. bas file. ). It can be found in the directory of your xlwings installation.

Which is better Openpyxl or Xlwings?

xlwings is the better choice if you want to split the design and code work. XlsxWriter/OpenPyxl is the better choice if it needs to be scalable and run on a server. If you need to generate PDF files at high speed, check out ReportLab.


1 Answers

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.

like image 190
3 revs, 3 users 91% Avatar answered Oct 14 '22 10:10

3 revs, 3 users 91%