Python学习笔记十四_操作Excel

一、安装第三方模块

Python操作excel使用xlrd、xlwt和xlutils模块。xlrd模块是读取excel的,xlwt模块是写excel的,xlutils模块是用来修改excel的。这几个模块使用pip安装即可。

如果电脑里面安装了多版本python时,安装第三方模块的时候写明python版本

python3 -m pip instatll xlutils

二、写Excel,xlwt模块

import xlwt
book = xlwt.Workbook()#新建一个excel对象
sheet = book.add_sheet('学生信息')#加sheet页
# sheet.write(0,0,'姓名')#行、列、写入的内容
# sheet.write(0,1,'年龄')
# sheet.write(0,2,'性别')
titles = ['姓名','年龄','性别']
for col,t in enumerate(titles):#写入表头
    sheet.write(0,col,t)#写入每行,第一个值是行,第二个值是列,第三个是写入的值
stus = [['Amy',20,''],['Ben',18,'']]
row = 1 #
for stu in stus:
    for clo,filed in enumerate(stu):
        sheet.write(row,clo,filed)#循环写入每行数据
    row += 1
book.save('stu.xls')#保存excel必须使用后缀名是.xls的,不是能是.xlsx的

三、读Excel,xlrd模块

import xlrd
book = xlrd.open_workbook('app_student.xls')#打开的这个excel必须存在,否则会报错
print(book.sheet_names()) #获取所有sheet页的名字
sheet = book.sheet_by_index(0)#根据sheet页的索引获取sheet页
sheet = book.sheet_by_name('sheet1')#根据sheet页的名字获取sheet页
print(sheet.cell(0,0))#指定sheet页面里面的行和列获取数据,#text:'id'
print(sheet.cell(0,0).value)#获取数据本身,去掉数据类型,id,去掉了text
print(sheet.row_values(0))#获取到第几行的内容,表头list
print(sheet.row_values(3))#返回是list[]
print(sheet.nrows)#获取到Excel里面总共有多少行
for i in range(sheet.nrows):#循环获取到每行的数据
    print(sheet.row_values(i))
print(sheet.ncols)#获取到Excel里面总共有多少列
print(sheet.col_values(0))#取第几列的数据 

四、修改Excel,xlutils模块 

import xlrd
from xlutils import copy#导入xlutils模块的复制excel模块
book = xlrd.open_workbook('stu.xls')#先用xlrd模块,打开一个excel
new_book = copy.copy(book)#通过xlutils模块中的copy方法,复制一份excel
sheet = new_book.get_sheet(0)#获取到新的excel里面的sheet页
titles = ['name','age','sex']
for col,t in enumerate(titles):#修改标题
    sheet.write(0,col,t)
new_book.save('stu.xls')#另存为原文件名
原文地址:https://www.cnblogs.com/dongrui624/p/8986641.html