python操作excel

如果安装了多个版本的python,在线安装第三方模块时,需要指定版本。例如:python3 -m pip install xlutils

一、读excel,用到xlrd模块

import xlrd
book = xlrd.open_workbook('app_student.xls')
sheet = book.sheet_by_index(0)#根据excel索引读取excel  , book.sheet_by_name('sheet1')通过name读取excel
print(sheet.cell(0,0).value)  #指定sheet页里面行和列获取数据

print(sheet.row_values(0))  #获取到第几行内容
print(sheet.row_values(1))
print(sheet.nrows)#获取到excel里面总共多少行
for i in range(sheet.nrows):  #循环获取每行数据
    print(sheet.row_values(i))

print(sheet.ncols)  #获取excel里面总共多少列
print(sheet.col_values(1)) #取第几列数据

二、写excel,用到xlwt模块

import pymysql,xlwt
def export_excel(table_name):
    coon=pymysql.connect(
        host='118.24.3.40',user='jxz',passwd='123456',
        port=3306,db='jxz',charset='utf8'
        #port必须写int类型
        #charset必须写utf8
    )#建立数据库连接字典
    cur=coon.cursor()#(cursor=pymysql.cursors.DictCursor)#建立游标,DictCursor返回字典
    sql="select * from %s;"%table_name     #占位符来表示查询条件筛选
    cur.execute(sql)
    # cur.execute('insert into stu(id,name,sex) VALUE (1223,"焦哥","男");')
    # cur.execute('insert into stu (id,name,sex) VALUE (1,"牛","女");')
    fileds=[filed[0] for filed in cur.description] #读取表头存在fileds列表里
    # print(cur.description)
    # for filed in cur.description:
    #     print(filed)
    # print(fileds)
    all_data=cur.fetchall()  #获取数据库里所有的数据
    book=xlwt.Workbook()
    sheet=book.add_sheet("sheet1")
    for col,filed in enumerate(fileds):  #通过k,v方式直接把表头循环写入到表格
        sheet.write(0,col,filed)
    row=1
    for data in all_data:  #循环每行数据
        # print(data)
        for col,filed in enumerate(data):  #每行数据以k,v方式循环写入表格
            # print(col,filed)
            sheet.write(row,col,filed)
        row+=1       #写完一行后,行数+1继续写入下一行数据
    book.save("%s.xls"%table_name)
export_excel("app_student")

三、修改excel,用到xlrd,xlutils模块

import xlrd
from xlutils import copy
book=xlrd.open_workbook('app_student.xls')#先用xlrd模块,打开一个excel
new_book=copy.copy(book) #通过xlutils这个模块里面的copy方法,复制一份excel

sheet = new_book.get_sheet(0) #获取sheet页,用的是xlutils里面的方法,xlrd的方法是book.sheet_by_index(0)
lis =['编号','名字','性别','年龄','地址','班级','手机号','金币']
for col,file in enumerate(lis): #把lis列表内容写入到表格
    sheet.write(0,col,file)
sheet.write(0,0,'编号')  #修改每个单元格的内容
sheet.write(0,1,'名字')
new_book.save('app_student.xls')#保存必须用xls,如果用xlsx的话微软是打不开,wps才可以打开
原文地址:https://www.cnblogs.com/xiaojing2017/p/9039944.html