Python------excel读、写、拷贝

#-----------------------读excel-----------------
#1 打开方式 索引、名字
#2 获取行数据 sheet.row_values(0);获取某行第n到m列(n闭合 m开)
#3 获取行号 sheet.nrows
#4 获取sheet页个数 book.nsheets

import xlrd

book = xlrd.open_workbook('student.xls')
#由索引打开
sheet=book.sheet_by_index(0)
#由名字打开
#book.sheet_by_name()
#value 去掉双引号
print(sheet.cell(0,0).value)

#获取0行所有列
print(sheet.row_values(0))
#获取0行1-3列,不包括第3列
print(sheet.row_values(0,1,3))
#获取行数
print(sheet.nrows)
#获取0列所有行
print(sheet.col_values(0))
#获取列数
print(sheet.ncols)
#获取excel中sheet数
print(book.nsheets)

#-----------------------写excel-----------------

#写excel
#1、建立新excel(此时不用增加excel名字)
#2、建立新sheet页
#3、写入
#4、保存

import xlwt

book=xlwt.Workbook() #创建excel
sheet=book.add_sheet('stu_info')
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')

#-----------------------拷贝excel-----------------
#拷贝需要xlutils(此模块下方法不能自动调出)

import xlrd
from xlutils import copy

#打开原来excel
book1=xlrd.open_workbook('user.xls')

#拷贝一个新的excel
new_book=copy.copy(book1)

sheet = new_book.get_sheet(0)

#sheet.write(1,3,'18')
new_book.save('user.xls')

猜你喜欢

转载自www.cnblogs.com/wenchengqingfeng/p/10101816.html