openpyxl中遇到TypeError: 'generator' object is not subscriptable

出現在原因在於 print(sheet.rows[1]) 


from openpyxl import *
import os

class excel_readWrite:
    def __init__(self, xls_name,base_url=None, pagetitle=None):

        self.xls_name=xls_name
        self.xls_path = os.path.join(readconfig.read('filepath', 'datapath'), self.xls_name)
        self.workbook=load_workbook(self.xls_path)
    def get_row(self,sheetName):
        sheet=self.workbook[sheetName]
        print(sheet.rows[1])

運行sheet.rows[1]時報錯

openpyxl目前版本爲2.5.12,因爲在這個版本中的sheet.rows 返回的爲一個生成器,所以不能採用此方法

 

解決方法爲:

1.更換openpyxl版本爲2.3.3 或者2.3.5

參看stackOverflow上找到了解決方法: 點擊鏈接

2.遍歷出生成器的結果


from openpyxl import *
import os

class excel_readWrite:
    def __init__(self, xls_name,base_url=None, pagetitle=None):

        self.xls_name=xls_name
        self.xls_path = os.path.join(readconfig.read('filepath', 'datapath'), self.xls_name)
        self.workbook=load_workbook(self.xls_path)
    def get_row(self,sheetName):
        sheet=self.workbook[sheetName]

        rowslist=[]
        for row in sheet.rows:
            rowlist = []
            for cell in row:
                cellValue=cell.value
                rowlist.append(cellValue)
            rowslist.append(rowlist)
        print(rowslist)

 

執行結果可以以二維數組的形式展現

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章