在Python中,操做excel有三种方式,分别为读取excel,写excel,修改excel
读excel
读excel,是使用的xlrd模块,在Python内置模块中,没有包含,须要本身手动安装
安装过程我就不详细介绍了,能够经过pip install xlrd方式直接安装好python
导入模块app
import xlrd
在读excel模块中,经常使用的函数以下
首先,打开一个excel函数
book = xlrd.open_workbook('user.xls') #打开一个excel文件
获取sheet页,有三种方法,以下excel
sheet = book.sheet_by_index(0) #经过索引顺序得到sheet页 sheet1= book.sheets()[0] #经过索引顺序得到sheet页 sheet2= book.sheet_by_name('sheet1') #经过sheet页名称得到
excel经常使用的读操做以下blog
print(sheet.cell(0,0).value) #指定sheet页面里边的行和列的数据 print(sheet.cell(0,2).value) #指定sheet页面里边的行和列的数据 print(sheet2.row_values(0)) #获取指定某行的数据 print(sheet2.col_values(0)) #获取指定某列的数据 print(sheet.nrows) #获取到excel里边总共有多少行 print(sheet.ncols) #获取到excel里边总共多少列 #循环读取每行数据,循环获得的是将每行数据,放到一个list中 for i in range(sheet.nrows): #循环获取到每行数据 print(sheet.row_values(i))
写excel
写excel,是使用的xlwd模块,在Python内置模块中,没有包含,须要本身手动安装索引
导入模块ip
import xlwd
在写excel模块中,经常使用的函数以下
首先,新建一个excelget
book = xlwt.Workbook() #新建一个excel
而后再excel 中添加一个sheet页it
sheet=book.add_sheet('sheet1') #添加一个sheet页面
而后再excel中进行写操做pip
sheet.write(0,0,'姓名') #行、列、写入的内容 sheet.write(0,1,'年龄') sheet.write(0,2,'性别')
循环写入
list = ['小明','小红','小黑'] [sheet.write(0,i,j) for i,j in enumerate(list)] #列表生成式,先循环list,而后sheet.write循环写入内容 #enumerate函数是将i从0开始自动加1,而后获取list中的每一个元素
最后编辑完成以后,保存excel,记住,保存excel 的时候,必定要用.xls结尾
book.save('stu.xls') #结尾必定要用.xls
修改excel
修改excel,是使用的xlutils模块,在Python内置模块中,没有包含,须要本身手动安装
首先在使用xlutils模块的以前,先用xlrd模块,打开一个excel
导入模块
import xlrd #导入xlrd模块,打卡一个excel from xlutils import copy #导入xlutils中的copy函数
读取excel
book = xlrd.open_workbook('user.xls') #先用xlrd模块,打开一个excel
而后使用xlutils模块中的copy函数,复制一个excel出来
new_book = copy.copy(book) #经过xlutils这个模块里面copy方法,复制一份excel
获取sheet页
sheet = new_book.get_sheet(0) #获取sheet页
而后进行写操做
lis = ['编号','名字','性别','年龄','地址','班级','手机号','金币'] for col,filed in enumerate(lis): sheet.write(0,col,filed)
最后保存excel,记住,保存excel 的时候,必定要用.xls结尾
new_book.save('app_student.xls')