python script to open excel workbook, and change the name of the first worksheet and execute stored proc
Question: i have this python script that's supposed to open an excel workbook from
directory and then change the name of the first worksheet and then run a
stored procedure on the first worksheet and the subsequent worksheet. When I
run the script it gives me an error - 'str' object attribute 'title' is read-
only. Any help or suggestions is appreciated.

    
    
    import os
    import pyodbc
    import openpyxl
    from openpyxl import load_workbook
    
    
    dirList = os.listdir("""\\Raw_Data\\HSRx""")
    
    #database connection
    #loop through excel workbooks
    #loop through excel sheets in each workbook
    #run stored proc on each worksheet
    #close files and disconnect to sql server
    conn = pyodbc.connect('DRIVER={SQLServer};SERVER=localhost;DATABASE=mydb;UID=myname;PWD=mypwd')
    cursor = conn.cursor()
    
    for n in dirList:
        path =os.path.join("""\\Raw_Data\\HSRx""",n)
        workbook = openpyxl.reader.excel.load_workbook(path)
        worksheets = workbook.get_sheet_names()
        sheet = ['None','None']
        i = 0
        print n
        for worksheet in worksheets:
            worksheet.title = "Sheetone"
            sheet[i] = "Sheetone"
            i += 1
            print worksheet
        cursor.execute("""exec SP_IMPORT_HSRx_Ins ?, ?, ?""",n,sheet[0],sheet[1])
        cursor.commit()
    
    
    conn.close()   
    

Here is the traceback:

    
    
    CS NOV20 12.xlsx Traceback (most recent call): 
      File "HSRXRecons.py", line 25, in <module> worksheet.title = "Sheetone" 
    AttributeError: 'str' object attribute 'title' is read-only 
    


Answer: `worksheet` is a string, because `get_sheet_names()` returns a list of
strings. You cannot assign attributes to strings.

    
    
    >>> 'Sheet1'.title = 'Sheetone'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'str' object attribute 'title' is read-only
    

To change the title pass the sheet name to `get_sheet_by_name`:

    
    
    workbook.get_sheet_by_name(worksheet).title = "Sheetone"
    

