如何通过Openpyxl从xlsx文件导入Python类?

问题描述 投票:-2回答:1

我有一个用Openpyxl打开的xlsx文件。每行包含student_id,first_name,second_name,parent_name和parent_email。

我创建了一个名为Students的方法

我希望程序占用每一行并将其分配给方法,例如。

Students(student_id = ['A -row number'], first_name = ['B -row number'], second_name = ['C - row number] ...etc

这样它就会遍历我的所有学生并自动添加它们

非常肯定答案在于循环,例如:

for row in ws.rows:
python class openpyxl
1个回答
0
投票

这种方式好多了。 Ditch Openpyxl,从csv文件中打开它。在csv文件中,我在A,B,C,D,E列中有每个单独的信息行

例如。 A1 =波特,哈利B1 =波特C1 =哈利......等等

import csv


#sorts all the student data into a class
class Students():
    def __init__(self,student_id, first_name,second_name,student_parent,parent_email):

        self.student_id = student_id
        self.first_name = first_name
        self.second_name = second_name
        self.student_parent = student_parent
        self.parent_email = parent_email


    def __repr__(self):
        return self.student_id + " " + self.first_name + " " +self.second_name + " " + self.student_parent + " " + self.parent_email


student_list = []

#opens the csv file, takes out the information and saves them in the Student Class
student_file = open('student_list.csv')
student_file_reader = csv.reader(student_file)
for row in student_file:
    row_string = str(row)
    row_parts1,row_parts2,row_parts3,row_parts4,row_parts5 = row_string.split(',')
    student_list.append(Students(row_parts1,row_parts2,row_parts3,row_parts4,row_parts5))

......并且你有它,一切都在列表中的对象中形成完美。

© www.soinside.com 2019 - 2024. All rights reserved.