1

我有这个 python 脚本,它应该从目录中打开一个 excel 工作簿,然后更改第一个工作表的名称,然后在第一个工作表和后续工作表上运行一个存储过程。当我运行脚本时,它给了我一个错误 - 'str' 对象属性 'title' 是只读的。任何帮助或建议表示赞赏。

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()   

这是回溯:

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 
4

1 回答 1

3

worksheet是一个字符串,因为get_sheet_names()返回一个字符串列表。您不能将属性分配给字符串。

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

要更改标题,请将工作表名称传递给get_sheet_by_name

workbook.get_sheet_by_name(worksheet).title = "Sheetone"
于 2012-12-07T17:44:19.813 回答