操作excel(读excel、修改excel)

练习

需求:只要你传入一个表名,就能把所有的数据导入出来,字段名是excel的表头

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

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

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

    3、循环写入excel

import pymysql,xlwt

def export_excel(table_name):

host, user, passwd, db = '11XXX', 'jxz', '123456', 'jxz'

coon = pymysql.connect(user=user, host=host, port=3306, passwd=passwd, db=db, charset='utf8')

  cur = coon.cursor()  # 建立游标,指定cursor类型返回的是字典

  sql = 'select * from %s ;'%table_name

  cur.execute(sql)  # 执行sql

  fileds = [filed[0] for filed in cur.description]  #所有的字段

  all_data = cur.fetchall()

  book = xlwt.Workbook()

  sheet  = book.add_sheet('sheet1')

  for col,filed in enumerate(fileds):   ######写表头的enumerate()获取位置和值,自动计算下标,fileds = ['id','name','sex','addr','gold','score']

for index,filed in enumerate(fileds):

  print(index,filed)####

           sheet.write(0,col,filed)

  row = 1  #行数

  for data in all_data:  #行

           for col, filed in enumerate(data):  # 控制列

                     sheet.write(row, col, filed)

           row+=1#每次写完一行,行就加1

  book.save('%s.xls'%table_name)

export_excel('app_student')

**

enumerate([list,list2])  #循环的时候,直接获取到下标,和值 二维数组

for index,value in enumerate([list,list2]):

    print(index,vlaue)

###读excel

import xlrd  #  xlrd读excel模块

book = xlrd.open_workbook('app_student.xls')

sheet = book.sheet_by_index(0)  #获取第一个sheet中的内容

# sheet2 = book.sheet_by_name('shee1')            也可以通过名字获取

# print(sheet.cell(0,0).value) #指定sheet页里面行和lie获取数据

# print(sheet.cell(1,0).value) #指定sheet页里面行和lie获取数据

# 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)  #总共多少列

print(sheet.col_values(0)) #取第几列的数据

###修改excel

指定安装 python3 –m pip XXX

如果你电脑里面装了多个版本的python

python3 -m pip instatll xlutils

python2 -m pip instatll xlutils

import xlrd

from xlutils import copy  #修改excel 模块  此方法比较特殊

book = xlrd.open_workbook('app_student.xls')

#先用xlrd模块,打开一个excel

new_book = copy.copy(book)   #修改先要copy

#通过xlutils这个模块里面copy方法,复制一份excel

sheet = new_book.get_sheet(0) #获取sheet页  这是xlutils的方法

lis = ['编号','名字','性别','年龄','地址','班级','手机号','金币']

for col,filed in enumerate(lis):

  sheet.write(0,col,filed)

new_book.save('app_student.xls')

原文地址:https://www.cnblogs.com/cslw5566/p/9026496.html