pip install openpyxl(写,支持xlsx格式)
新建文件
#1.新建一个Excel
wb=workbook.Workbook()
#2.创建表单的方法 创建一个自定义的表单
wb.create_sheet('info',index=0)
#3.另存为 保存工作簿
wb.save('D:\excel\pythonexcel.xlsx')
打开文件写入
#1.打开的工作簿
wb=load_workbook(filename)
#2.定位到表单
sheet=wb['info']
#3.cell(I行,J列),必须从1开始
sheet.cell(1,1).value='姓名'
#4.保存工作簿
wb.save('D:\excel\pythonexcel.xlsx')
源码
import os
from openpyxl import workbook
from openpyxl import load_workbook
'''
支持xlsx格式写
'''
class excel():
def wirteExcle(self,filename,data):
wb=workbook.Workbook()
wb.create_sheet('info',index=0)
wb.save(filename)
wb=load_workbook(filename)
sheet=wb['info']
c=1
for students in data:
sheet.cell(1,1).value='姓名'
sheet.cell(1,2).value='年龄'
sheet.cell(c,1).value=students['name']
sheet.cell(c,2).value=students['age']
c+=1
wb.save(filename)
wb.close()
if __name__=='__main__':
str= [{'name':'zhangshan','age':19},
{'name':'lisi','age':28},
{'name':'wangwu','age':59}]
exl = excel()
exl.wirteExcle('D:\excel\pythonexcel.xlsx',str)
打印execel内容