Python学习之==>Excel操作

一、简介

  使用Python读、写、修改excel分别需要用到xlrd、xlwt以及xlutils模块,这几个模块使用pip安装即可。

二、读excel

 1 import xlrd
 2 book = xlrd.open_workbook('app_student.xls')
 3 sheet = book.sheet_by_index(0)        # 根据下标来获取sheet页
 4 sheet = book.sheet_by_name('sheet1')  # 根据sheet名来获取sheet页
 5 print(sheet.cell(0,0))                # 指定excel里面的行和列来获取数据
 6 print(sheet.cell(0,0).value)          # 加上value直接取到单元格里面的值
 7 print(sheet.row_values(0))            # 获取到第几行的内容,放到一个list里面
 8 print(sheet.col_values(0))            # 获取到第几列的数据,放到一个list里面
 9 print(sheet.nrows)                    # 获取到excel里面一共有多少行
10 print(sheet.ncols)                    # 获取到excle里面一共有多少列
11 # 循环获取每行数据
12 for i in range(sheet.nrows):          
13     print(sheet.row_values(i))
14 # 循环获取每列数据
15 for i in range(sheet.ncols):            
16     print(sheet.col_values(i))

三、写excel

1 import xlwt
2 book = xlwt.Workbook()            # 新建一个excel
3 sheet = book.add_sheet('sheet1')  # 增加sheet页
4 sheet.write(0,0,'姓名')            # 写入的内容,前面两个元素分别代表行和列
5 sheet.write(0,1,'年龄')
6 sheet.write(0,2,'性别')
7 book.save('stu.xls')              # 保存excel,结尾一定要用.xls

四、修改excel

 1 import xlrd
 2 from xlutils import copy              # xlutils模块导入方法需要这样用,直接导入模块不能用
 3 book = xlrd.open_workbook('stu.xls')  # 先用xlrd模块,打开一个excel
 4 new_book = copy.copy(book)            # 通过xlutils这个模块里面copy方法,复制一份excel
 5 sheet = new_book.get_sheet(0)         # 获取sheet页
 6 lis = ['编号','名字','性别','年龄','地址','班级','手机号','金币']
 7 # 使用enumerate可以直接取到list元素的下标和值从而进行循环写入excel
 8 for col,filed in enumerate(lis):
 9     print(col,filed)
10     sheet.write(0,col,filed)
11     new_book.save('stu.xls')
原文地址:https://www.cnblogs.com/L-Test/p/9199690.html