Python store class list data in excel file via pandas

import datetime
import pandas as pd
import time

class Book():
    def __init__(self,id,name,isbn,comment,content,summary,title,topic):
        self.id=id
        self.name=name
        self.isbn=isbn
        self.comment=comment
        self.content=content
        self.summary=summary
        self.title=title
        self.topic=topic

t1=datetime.datetime.now()
print(t1)
books_list=[]

arr=range(1,1000001)
for i in arr:
    books_list.append(Book(i,f'Name_{i}',f'ISBN_{i}',f'Comment_{i}',f'Content_{i}',f'Summary_{i}',f'Title_{i}',f'Topic_{i}'))

book_data=[]
for bk in books_list:
    dic={
         'Id':bk.id,
        'Name':bk.name,
        'Isbn':bk.isbn,
        'Comment':bk.comment,
        'Content':bk.content,
        'Summary':bk.summary,
        'Title':bk.title,
        'Topic':bk.topic
    }
    book_data.append(dic)

t1=datetime.datetime.now()
print(f'before book_data,now is {t1}')
df=pd.DataFrame(book_data)
excelFile=datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
df.to_excel(f'{excelFile}.xlsx',index=False,sheet_name='book_sheet_1')
print(f'pd.DataFrame(book_data),now:{datetime.datetime.now()},Time cost:{datetime.datetime.now()-t1},in {excelFile}')

time.sleep(5)

t1=datetime.datetime.now()   
df=pd.DataFrame([bk.__dict__ for bk in books_list])
excelFile=datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
df.to_excel(f'{excelFile}.xlsx',index=False,sheet_name='book___dict___1')
print(f'[bk.__dict__ for bk in books_list],now:{datetime.datetime.now()},Time cost:{datetime.datetime.now()-t1},in {excelFile}')
print(f'dic len:{len(book_data)},type:{type(book_data)}')

 

image

 

 

image

 

 

image

 

posted @ 2025-11-26 20:47  FredGrit  阅读(0)  评论(0)    收藏  举报