操作excel

--写excel---
import  xlwt
book=xlwt.Workbook()#新建一个Excel
sheet=book.add_sheet('sheel1')#加sheet页
sheet.write(0,0,'姓名')
sheet.write(0,1,'年龄')
sheet.write(0,2,'性别')
book.save('stu.xls')#结尾一定要用.xls

--修改excel--
import xlrd#导入读模块
from xlutils import copy#从修改模块中导入copy
book = xlrd.open_workbook('app_student.xls')#先用xlrd模块,打开一个excel
new_book = copy.copy(book)#通过xlutils这个模块里面copy方法,复制一份excel
sheet = new_book.get_sheet(0) #获取sheet页
lis = ['编号','名字','性别','年龄','地址','班级','手机号','金币']
for col,filed in enumerate(lis):#循环取lis的下标和值
sheet.write(0,col,filed)#按下标写入列和值
new_book.save('app_student.xls')#新存一个excel名字和原来一样,否则会新建


--读excel--
import xlrd
book = xlrd.open_workbook('app_student.xls')
sheet = book.sheet_by_index(0)
sheet2 = book.sheet_by_name('shee1')
print(sheet.cell(0,0).value) #指定sheet页里面行和lie获取数据
print(sheet.cell(1,0).value) #指定sheet页里面行和lie获取数据
print(sheet.row_values(0)) #这个获取到第几行的内容
print(sheet.row_values(1)) #这个获取到第几行的内容
print(sheet.nrows) #获取到excel里面总共有多少行
for i in range(sheet.nrows): #循环获取到每行数据
print(sheet.row_values(i))
print(sheet.ncols) #总共多少列
print(sheet.col_values(0)) #取第几列的数据


猜你喜欢

转载自www.cnblogs.com/irisx/p/9001990.html