从多个Excel文件中检索值

时间:2018-05-01 14:39:06

标签: python excel tkinter dialog

我正在尝试使用以下函数从多个Excel文件中读取值:

def uploadtranscipt(self):

    self.student=[]
    self.transcript_upload = tkFileDialog.askopenfilename(filetypes=(("Excel files", ".xls"), ("All files", "*.*")),multiple=1)
    self.student.append(self.transcript_upload)
    self.book = xlrd.open_workbook(str(self.transcript_upload))
    self.sheet = self.book.sheet_by_index(0)
    for i in self.student:
        for stu in i :
            self.id = (self.sheet.cell(0,0).value).encode("utf-8")
            print self.id
            self.name = (self.sheet.cell (0,1).value).encode("utf-8")
            print self.name
            self.dep = (self.sheet.cell(0, 2).value).encode("utf-8")
            print self.dep
            self.gpa = self.sheet.cell(0, 3).value
            print self.gpa

但是,引发了以下异常:

  

IOError:[Errno 22]无效模式('rb')或文件名:“(u'C:/Users/r.la/Desktop/programming 2 / Transcripts / Sample27.xls',u'C:/ Users /r.la/Desktop/programming 2 / Transcripts / Sample26.xls')“

1 个答案:

答案 0 :(得分:0)

tkFileDialog.askopenfilename返回一个文件名元组。但是,xlrd.open_workbook只打开一个文件名。 如果要从多个文件中读取数据,请使用for循环一次处理一个文件:

def uploadtranscript(self):

    self.student=[]
    self.transcript_upload = tkFileDialog.askopenfilename(filetypes=(("Excel files", ".xls"), ("All files", "*.*")),multiple=1)
    self.student.append(self.transcript_upload)
    for transcript_fname in self.transcript_upload:
        self.book = xlrd.open_workbook(transcript_fname)
        self.sheet = self.book.sheet_by_index(0)
        for i in self.student:
            for stu in i:
                self.id = (self.sheet.cell(0,0).value).encode("utf-8")
                print self.id
                self.name = (self.sheet.cell (0,1).value).encode("utf-8")
                print self.name
                self.dep = (self.sheet.cell(0, 2).value).encode("utf-8")
                print self.dep
                self.gpa = self.sheet.cell(0, 3).value
                print self.gpa