xlwt
import xlwtwb = xlwt.Workbook()# 添加一个表ws = wb.add_sheet('test')# 3个参数分别为行号,列号,和内容# 需要注意的是行号和列号都是从0开始的# ws.write(0, 0, '第1列') # 一个一个来# ws.write(0, 1, '第2列')# ws.write(0, 2, '第3列')for i in range(3): for j in range(2): ws.write(i, j, f'第{i+1}行,第{j+1}列')# 保存excel文件wb.save('./test.xls')
效果:
openpyxl
from openpyxl import Workbookoutwb = Workbook()outws = outwb.worksheets[0]mongoDB_data = [{'name':'周','age':18,'sex':'男'}, {'name':'王','age':19,'sex':'男'}, {'name':'李','age':16,'sex':'女'}]outws.append(['姓名','年龄','性别']) # 先添加一行表头# 遍历外层列表for new_dict in mongoDB_data: a_list = [] # 遍历内层每一个字典dict,把dict每一个值存入list for item in new_dict.values(): a_list.append(item) # sheet直接append list即可 outws.append(a_list)outwb.save(r'test.xlsx')print('数据存入excel成功')
效果:
xlsxwriter
import xlsxwriter as xwworkbook = xw.Workbook('text.xls') # 创建工作簿worksheet1 = workbook.add_worksheet("sheet1") # 创建子表worksheet1.activate() # 激活表title = ['姓名','年龄','性别'] # 设置表头data = [['周',18,'男'],['王',19,'男'],['李',16,'女']]worksheet1.write_row('A1',title) # 从A1单元格开始写入表头i = 2 # 从第二行开始写入数据for j in range(len(data)): insertData = [data[j][0],data[j][1],data[j][2]] row = 'A' + str(i) worksheet1.write_row(row, insertData) i += 1workbook.close() # 关闭表
效果:
pandas
import pandas as pddata = [['周','王','李'],[18,19,16],['男','男','女']]dfData = { # 用字典设置DataFrame所需数据 '姓名':data[0], '年龄':data[1], '性别':data[2] }df = pd.DataFrame(dfData) # 创建DataFramedf.to_excel('text.xlsx',index=False) # 存表,去除原始索引列(0,1,2...)
效果:
openpyxl
import openpyxl as opdata = [['周','王','李'],[18,19,16],['男','男','女']]wb = op.Workbook() # 创建工作簿对象ws = wb['Sheet'] # 创建子表ws.append(['姓名','年龄','性别']) # 添加表头for i in range(len(data[0])): d = data[0][i], data[1][i], data[2][i] ws.append(d) # 每次写入一行wb.save('test.xlsx')
效果:
来源地址:https://blog.csdn.net/MAKABAKA__ZJC/article/details/128834033