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中遇到TypeError: 'generator' object is not subscriptable_第1张图片

openpyxl目前版本为2.5.12,因为在这个版本中的sheet.rows 返回的为一个生成器,所以不能采用此方法

 

解决方法为:

1.更换openpyxl版本为2.3.3 或者2.3.5

参看stackOverflow上找到了解决方法: 点击链接

openpyxl中遇到TypeError: 'generator' object is not subscriptable_第2张图片

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)

 

执行结果可以以二维数组的形式展现

你可能感兴趣的:(Python,selenium)