'Any way to create a new worksheet using xlwings?

Using Python xlwings, how can I create a new worksheet?



Solution 1:[1]

import xlwings as xw
wb = xw.Book()
wb.sheets.add()

See also the docs.

Solution 2:[2]

I use the following helper function to add a sheet if it is not yet existing or get/activate it, in case it is already present:

def addActivate(wb, sheetName, template=None):
    try:
        sht = wb.sheets(sheetName).activate()
    except com_error:
        if template:
            template.sheets["Template"].api.Copy(wb.sheets.active.api)
            sht = wb.sheets["Template"].api.Name = sheetName
        else:
            sht = wb.sheets.add(sheetName)
    return sht

It also allows to define the name of a sheet name to be used as template for the new sheet.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Robert