3

i am using this:

from win32com.client import Dispatch
excel_file = Dispatch("Excel.Application")
excel_file.Workbooks.Open(excel_result_path)
excel_file.Visible = 1
mySheet = excel_file.Worksheets.Add()
mySheet.Name = "name"

which works fine. the only problem is, if the sheet allready exists, i get an error telling me, that the sheet already exists

File "..\dynamic.py", line 554, in setattr pywintypes.com_error: (-2147352567, 'Ausnahmefehler aufgetreten.', (0, 'Microsof t Excel', 'Kann einem Blatt nicht den gleichen Namen geben wie einem anderen Bla tt, einer Objektbibliothek oder einer Arbeitsmappe, auf die Visual Basic Bezug n immt.', 'xlmain11.chm', 0, -2146827284), None)

so my question is, how can i check if an excel-sheet-name allready exists ?

der_die_das_jojo
  • 893
  • 1
  • 9
  • 21
  • Could you catch the exception? Or see if "name" is in wb.Sheets.Name? What do you want to do if it exists already? – doctorlove Sep 18 '13 at 08:50

2 Answers2

4
'name' in [excel_file.Sheets(i).Name for i in range(1,excel_file.Sheets.Count+1)]
vikash
  • 56
  • 2
0

Slightly more readable solution:

'name' in [sheet.Name for sheet in excel_file.Sheets]