批量构造数据写入excel,读取excel数据转换成字典格式

#写入excel文件内容,读取excel文件内容json格式
#

import pandas as pd
from faker import Faker



fake = Faker(locale='zh_CN')#中文zh_CN
tmp = []
tcpColunm = ['id','name','url','address']
for i in range(500):
    dic = {'id':i,'name':fake.name(),'url':fake.url(),'address':fake.address()}
    tmp.append(dic)
print('写入excel数据内容:\n',tmp)

#手动创建test.xlsx文件,放在同目录下。构造数据,写入xlsx
writer = pd.ExcelWriter('test.xlsx')
df2 = pd.DataFrame(data=tmp,columns=tcpColunm)
df2.to_excel(writer,'SheetW',index=False)
writer.save()
writer.close()

print('\n-----------------分割线----------------------\n')
#读取test.xlsx中的数据,转换成字典格式
dfs2 = pd.read_excel('test.xlsx')
datadic = []
for i in dfs2.index.values:#获取行号索引并对其遍历
    row_data = dfs2.loc[i, dfs2.columns.values].to_dict()#iloc根据行号来索引,loc根据index来索引
    datadic.append(row_data)
print('xlsx数据转换为字典是:\n{0}'.format(datadic))






猜你喜欢

转载自blog.csdn.net/songpeiying/article/details/115110817
今日推荐