'''
python操作excel,python操作excel使用xlrd、xlwt和xlutils模块,
xlrd模块是读取excel的,xlwt模块是写excel的,xlutils是用来修改excel的。
这几个模块使用pip安装即可,下面是这几个模块的使用。
'''
# 例1:
# import xlwt
# xld = xlwt.Workbook() # 新建一个excel文件
# sheet = xld.add_sheet('sheet1') # 添加一个sheet
# sheet.write(0,0,'姓名')#第一行第一列
# sheet.write(0,1,'性别')
# sheet.write(0,2,'年龄')
# xld.save('stu.xls')# 读的时候可以是xlsx的格式,但是写的时候不允许
# xld.save(r'C:UsersAdministratorPicturesstu.xls') # 存指定位置
# 例2
# import xlwt
# title = [ '姓名','年龄','性别','分数']
#
# stus = [
# ['mary', 20, '女', 89.9],
# ['nacy', 20, '女', 90],
# ['lisa', 20, '女', 99],
# ['cindy', 20, '女', 70]
# ]
#
# book = xlwt.Workbook()
# sheet = book.add_sheet('sheet1')
# column = 0 #控制列
# for t in title:
# sheet.write(0,column,t)
# column+=1
# row =1 # 控制行
#
# for stu in stus:
# new_col = 0 # 控制列
# for s in stu:# 控制写每一列的
# sheet.write(row,new_col,s)
# new_col+=1
# row+=1
# book.save('stu.xls')
# book.save(r'C:UsersAdministratorPicturesstu.xls')
# 例 3
# import xlwt
# stus = [
# [ '姓名','年龄','性别','分数'],
# ['mary', 20, '女', 89.9],
# ['nacy', 20, '女', 90],
# ['lisa', 20, '女', 99],
# ['cindy', 20, '女', 70]
# ]
#
# book = xlwt.Workbook()
# sheet = book.add_sheet('sheet1')
# row = 0
# for stu in stus:
# col = 0 # 控制列
# for s in stu:
# sheet.write(row,col,s)
# col+=1
# row+=1
#
# book.save('stu.xls')
# book.save(r'C:UsersAdministratorPicturesstu.xls')
# 读取excel 文件
# import xlrd
# book = xlrd.open_workbook('stu.xls') # 打开一个excel
# sheet = book.sheet_by_index(0)# 根据 下标 获取内容
# # sheet = book.sheet_by_name('sheet1') # 根据 名字 获取内容
# print(sheet.cell(0,0))# 指定行列获取 打印结果:text:'姓名'
# print(sheet.cell(1,0)) # 指定行列获取 打印结果:text:'mary'
# print(sheet.cell(1,0).value) # 打印结果:mary
#
# print(sheet.ncols) # 获取一共多少列 打印结果:4
# print(sheet.nrows) # 获取一共多少行 打印结果:5
#
# print(sheet.get_rows())
# for i in sheet.get_rows():
# print(i) # 获取所有内容
# # 打印结果是:[text:'姓名', text:'年龄', text:'性别', text:'分数']
# # [text:'mary', number:20.0, text:'女', number:89.9]
# # [text:'nacy', number:20.0, text:'女', number:90.0]
# # [text:'lisa', number:20.0, text:'女', number:99.0]
# # [text:'cindy', number:20.0, text:'女', number:70.0]
#
# print(sheet.row_values(0)) # 获取第0行的数据 打印结果:['姓名', '年龄', '性别', '分数']
# for i in range(sheet.nrows):
# print(sheet.row_values(i)) # 取第几行的数据
# #打印结果是:['姓名', '年龄', '性别', '分数']
# # ['mary', 20.0, '女', 89.9]
# # ['nacy', 20.0, '女', 90.0]
# # ['lisa', 20.0, '女', 99.0]
# # ['cindy', 20.0, '女', 70.0]
#
# print(sheet.col_values(1)) # 获取第1列的数据 打印结果:['年龄', 20.0, 20.0, 20.0, 20.0]
# 修改excel 内容
from xlutils.copy import copy
import xlrd
# 修改stu, 把mary的分数修改为 0
book1 = xlrd.open_workbook('stu.xls')
book2 = copy(book1)
sheet = book2.get_sheet(0) # 操作第几个sheet页
sheet.write(1,3,0) # 第一行第三列修改为 0
book2.save('stu_new.xls') #