码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-07-22 00:27:18      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:imp   拷贝   int   add   row   多少   文件   rom   book   

一、写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

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

标签:imp   拷贝   int   add   row   多少   文件   rom   book   

原文地址:https://www.cnblogs.com/xzzxyz-lyn/p/9348245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!