向左转向右走

导航

python学习-常用模块8-操作excel,操作写、查、改

一、写excel
import xlwt  #只能写excel
book = xlwt.Workbook() #创建excel
sheet = book.add_sheet('sru_info')#加一个sheet页
sheet.write(0,0,'学生编号')
sheet.write(0,1,'学生姓名')
sheet.write(0,2,'成绩')
sheet.write(1,0,'1')
sheet.write(1,1,'李广')
sheet.write(1,2,'98.2')
book.save('stu.xls')

二、查看excel
import xlrd #只能读excel
# 1、打开excel
book = xlrd.open_workbook('lyn.xls')#打开一个excel
print(book.nsheets) #获取到excel里面总共有多少个sheet页
sheet = book.sheet_by_index(0)#获取sheet页,根据索引获取,第几页
# book.sheet_by_name('sheet1')#根据sheet页的名字获取
# 下面就是获取数据
# 指定行和列,获取某个单元格里面的内容
print(sheet.cell(0,0).value)# .value使获取的数据正常
print(sheet.cell(1,0).value)
# 获取某一行的数据
print(sheet.row_values(0))
print(sheet.row_values(1))
# 获取sheet 页里面总共有多少行
print(sheet.nrows)
# 获取某一列的数据
print(sheet.col_values(0))
print(sheet.col_values(1))
# 获取sheet 页里面总共有多少列
print(sheet.ncols)

三、修改excel

# 思路
# 1、打开原来的excel
# 2、拷贝一个新的excel
# 3、获取一个sheet页
# 4、修改excel
# 想要修改更多数据,可以循环修改
# 5、关闭excel
import xlrd
from xlutils import copy
# copy.copy()#要用这个方法复制原来的文件
book1 = xlrd.open_workbook('lyn.xls')#打开原来的excel
new_book =copy.copy(book1)#拷贝一个新的excel
sheet = new_book.get_sheet(0)#获取一个sheet页
# 修改excel
sheet.write(1,3,'18')
sheet.write(1,1,'萧何')
new_book.save('lyn.xls')#关闭excel

posted on 2018-07-21 22:03  向左转向右走  阅读(283)  评论(0编辑  收藏  举报