8

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

Felix Zumstein
  • 6,737
  • 1
  • 30
  • 62
hd810
  • 197
  • 1
  • 2
  • 8
  • Maybe this helps: http://docs.xlwings.org/quickstart.html#interact-with-excel-from-python – ρss Oct 14 '14 at 12:42
  • 1
    @ρss thanks. The document only gives how to get an existing worksheet rather than create a new one. – hd810 Oct 14 '14 at 14:01

2 Answers2

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

See also the docs.

Felix Zumstein
  • 6,737
  • 1
  • 30
  • 62
  • I am trying to create a new sheet and I get: `TypeError: add() missing 1 required positional argument: 'self'` after I have given it a name between quotations. – FaCoffee Apr 30 '18 at 14:16
1

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.

Robert
  • 1,357
  • 15
  • 26