python学习笔记(八)python操作Excel

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

二、xlwt模块,xlwt模块用来写一个新的Excel。

 

import xlwt
title = ['姓名','年龄','性别','分数']
stus = [['mary1',20,'',89.9],['mary2',21,'',89.9],['mary3',22,'',89.9],['mary4',23,'',89.9]]
book = xlwt.Workbook() #新建一个excel对象
sheet = book.add_sheet('stu') #添加一个名为stu的sheet页
for i in range(len(title)):  #循环title
    sheet.write(0,i,title[i])  #将title中元素写入,作为表头
row=1
for i in stus:  
    col = 0
    for j in i:
        sheet.write(row,col,j)
        col+=1
    row+=1
book.save('stu.xls')

 三、导出数据库某个表中的数据到excel中

1.首先介绍函数enumerate([list1,list2,list3])的作用,这个函数在循环的时候可以直接获取到下标和值

来看看下面的例子就明白了

list = ['id','name','sex','addr','phone','score','gold']
for index ,value in enumerate(list):
     print(index,value)

输出list的下标和元素值,输出结果如下

0 id
1 name
2 sex
3 addr
4 phone
5 score
6 gold

写一个通用的函数,从数据库中导出某个表的所有数据,只要你传入一个表名,就能把所有的数据导入出来,字段名是excel的表头

       1、要动态获取到表的字段 cur.description能获取到表的字段

             fileds = [ filed[0] for filed in cur.description ]

       2、获取数据了 select * from "%s" % table_name

       3、循环写入excel

import xlwt
def export_excel(table_name):
    host, user, passwd, db = '118.24.3.40', 'jxz', '123456', 'jxz'
    coon = pymysql.connect(host=host,user=user,passwd=passwd,db=db,port=3306,charset='utf8')
    cur = coon.cursor() #建立游标,可以指定游标类型
    sql = 'select * from %s'% table_name
    cur.execute(sql)
    fields = [field[0] for field in cur.description]  #获取数据库表字段,存入列表fields中
    all_data = cur.fetchall() #获取所有数据
    book = xlwt.Workbook()
    sheet = book.add_sheet('sheet1')
    for col ,field in enumerate(fields):  #循环写表头
        sheet.write(0,col,field)
    row =1  #从第一行开始写数据
    for data in all_data:#all_data存的是所有数据,数据库中每一行数据是all_data中的一个元素,也就是循环数据库表中的每一行数据
        for col,field in enumerate(data): #将每一行数据写入到excel中的某一行
            sheet.write(row,col,field)
        row+=1   #每写完一行,行数加1
    book.save('%s.xls'%table_name)

四、读取excel中内容

import xlrd
book = xlrd.open_workbook('app_student.xls')#先用xlrd模块,打开一个excel
sheet = book.sheet_by_index(0)#根据索引获取sheet页
sheet = book.sheet_by_name('info')#根据sheet页名称获取sheet页
print(sheet.cell(0,0).value)#指定sheet页里的行和列获取数据
print(sheet.cell(0,1).value)#指定sheet页里的行和列获取数据
print(sheet.row_values(0))#获取到第1行的数据
print(sheet.row_values(1))#获取到第2行的数据
print(sheet.nrows)#获取excel中总共有多少行数据
print(sheet.ncols)#获取excel中总共有多少列
print(sheet.col_values(0))#获取第1列数据
for rownum in range(sheet.nrows):
print(sheet.row_values(rownum)) #取每行的数据

五、修改excel中内容

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页
lis = ['编号','名字','性别','年龄','地址','班级','手机号','金币']
for clo,filed in enumerate(lis): #获取list的下标和值,循环写入
    sheet.write(0,clo,filed)
new_book.save('app_student.xls')
原文地址:https://www.cnblogs.com/mululu/p/8946603.html