简体   繁体   中英

How do I import from xlsx file via Openpyxl into a Python Class?

I have an xlsx file which opens with Openpyxl. Each row contains student_id, first_name, second_name, parent_name and parent_email.

I have created a method called Students

I want the program to take each row and assign it to the method eg.

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

so that it cycles through all of my students and automatically adds them

pretty sure the answer lies in a loop such as:

for row in ws.rows:

This way was much better. Ditch Openpyxl, open it from a csv file. In the csv file I have rows each individual bit of information in columns A,B,C,D,E

eg. A1 = Potter, Harry B1 = Potter C1 = Harry... etc

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

...and there you have it, all in formation in objects within a list perfect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM