操作Excel

一、写Excel

import xlwt
book = xlwt.Workbook()#创建excel
sheet = book.add_sheet('stu_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.87)
book.save('stu.xls')#一定要用xls的

 二、修改Excel

import xlrd
from xlutils import copy
book1 = xlrd.open_workbook('stu.xls')
#打开原来的excel
new_book = copy.copy(book1)
#拷贝一个新的excel
sheet = new_book.get_sheet(0)
#获取第一个sheet页
sheet.write(1,2,'60')
sheet.write(1,1,'')
new_book.save('stu.xls')

 三、读Excel

#xlwt #只能写excel
import xlrd #只能读
book = xlrd.open_workbook('stu.xls')
print(book.nsheets)#获取到excel里面总共有多少个sheet页  输出结果:1
sheet = book.sheet_by_index(0)

#book.sheet_by_name('stu_info')#
print(sheet.cell(0,0).value)  #指定行和列,获取某个单元格里面的内容 输出结果:学生编号
print(sheet.cell(1,0).value)   #输出结果:1:

print(sheet.row_values(0))#获取某一行的数据   输出结果:['学生编号', '学生姓名', '成绩']
print(sheet.row_values(1))#获取某一行的数据   输出结果:['1', '王', '60']
print(sheet.nrows)#这个就是excel里面总共有多少行  输出结果:2
print(sheet.col_values(0))#某一列的数据    输出结果:['学生编号', '1']
print(sheet.col_values(1))#某一列的数据    输出结果:['学生姓名', '王']
print(sheet.ncols)#总共有多少列    输出结果:3
原文地址:https://www.cnblogs.com/Noul/p/9310670.html