Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xlwings activate variable sheet name

Tags:

xlwings

I'm trying to perform two actions: 1) Check to see if a worksheet exists in a workbook using xlwings 2) Use a variable name to activate the worksheet using xlwings.

The worksheet name is a variable, so I can't use the sheets[0] option or sheets['name'] option.

import xlwings as xw
app = xw.apps.active
wb = app.books.active
key1 = 'BUS'
if key1 in wb:
    sht = wb.sheets.activate(key1)
else:
    sht = wb.sheets.add(key1)

I get the error: AttributeError: 'Sheets' object has no attribute 'activate'

like image 916
twonkie Avatar asked Feb 24 '26 17:02

twonkie


1 Answers

You should slightly rewrite your code to get this working. Tested this by opening a new Excel workbook and running the code a few times.

# python 3.7.3
# xlwings 0.15.8

import xlwings as xw

app = xw.apps.active
wb = app.books.active

key1 = 'BUS'

if key1 in [sh.name for sh in wb.sheets]:
    sht = wb.sheets[key1]
else:
    sht = wb.sheets.add(key1)

Changes:

  • You should iterate over the sheet names instead of the sheet objects
  • There is no need to activate a sheet in xlwings. As soon as you assign the sheet you want to work in to your sht variable, all actions will be performed on this sheet. You can also create a separate variable for every sheet (e.g. sht_bus, sht_train, ...)
like image 127
Steven Van Dorpe Avatar answered Feb 27 '26 07:02

Steven Van Dorpe