0

please forgive me if this is an ignorant question. I am fairly new to coding and Python and I have been trying all day to figure this out.

I am trying to write a script where the user provides a list of sheet-names and I will create an Excel workbook and a sheet in the workbook for each sheet-name provided. While coding, I wanted to use a variable (like ws1) to refer to each worksheet, but I don't know ahead of time how many sheets will be required...depends on how many names user provides.

So I am currently using 'len' to get the count of names in the list (and to know how many sheet-name variables I will need (ie. ws1, ws2, etc.). I thought I would run a loop to assign each sheet-name to one of the variables (that I want to create on-the-fly, but I haven't been able to find info how to do this.

Each variable will begin with 'ws' followed by the next available number (1,2,3, etc) until the range is complete. I thought I would concatenate using something like this:

counter = 0
for i in range(len(sheet_names_lst)):
    sht_name="ws%d: % (i+1)
    'ws'+counter = wb.create_sheet("mysheet_one")

...but I get an error "Expression cannot be assignment target"

Any help would be greatly appreciated. Thanks CB

  • 1
    Put them in a list instead. `worksheets = []` and `worksheets.append(wb.create_sheet("mysheet_one")`. – Loocid Feb 04 '22 at 01:04
  • Or put them in a dictionary where the keys are the names from `sheet_names_lst`. `sheets = {name: wb.create_sheet(name) for name in sheet_names_lst}`, or something along those lines. – Samwise Feb 04 '22 at 01:07
  • Some languages will allow you to create variables that way, but Python does not. What you can do is create a [dictionary](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) that stores all of your sheets. The question linked to in the close reason has examples of how to do this. – hostingutilities.com Feb 04 '22 at 01:11
  • Thank you for quick responses Loocid, Samwise, and hostingutilities.com. Much appreciated!! – CatButtler Feb 04 '22 at 02:46

0 Answers0