• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

博客园    首页    新随笔    联系   管理    订阅  订阅
python--操作excel

一、写excel模块

import xlwt

book = xlwt.Workbook()#新建一个excel

sheet = book.add_sheet('sheet1')#加sheet页

sheet.write(0,0,'姓名')#行、列,写入的内容

sheet.write(0,1,'年龄')

sheet.write(0,2,'性别')

book.save('stu.xls')#结尾一定要用.xls


二、读excel模块

import xlrd

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

sheet = book.sheet_by_index(0)

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里面总共有多少行

print(sheet.ncols)  #总共多少列

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

循环获取每行数据

1 for i in range(sheet.nrows):  #循环获取到每行数据
2     print(sheet.row_values(i))

循环获取每列数据

1 for i in range(sheet.ncols):#循环获取到每列数据
2     print(sheet.col_values(i))


三、修改excel

在打开excel时,后边加上formatting_info=True,可以把原excel里的样式也拷贝到新excel中
将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 col,filed in enumerate(lis):#enumerate打印列表下标及元素,循环列表时,下标会自增
    sheet.write(0,col,filed)

new_book.save('app_student.xls')


四、通用导出excel方法

需求:
  只要你传入一个表名,就能把所有的数据导入出来,字段名是excel的表头
  1、要动态获取到表的字段 cur.description能获取到表的字段
    fileds = [ filed[0] for filed in cur.description ]
  2、获取数据了  select * from "%s"  % table_name
  3、循环写入excel

 1 import pymysql,xlwt
 2 def export_excel(table_name):
 3     host, user, passwd, db = '118.24.3.40','jxz','123456','jxz'
 4     coon = pymysql.connect(user=user,host=host,port=3306,passwd=passwd,db=db,charset='utf8')
 5     cur = coon.cursor() #建立游标,指定cursor类型返回的是字典
 6     sql='select * from %s;'%table_name
 7     cur.execute(sql)#执行sql
 8     fileds = [ filed[0] for filed in cur.description ]#获取所有的字段名用作表头
 9     all_data = cur.fetchall()#获取所有数据
10     print(all_data)
11     book = xlwt.Workbook()
12     sheet =book.add_sheet('sheet1')
13 
14     for col,filed in enumerate(fileds):#写表头
15         sheet.write(0,col,filed)#行,列,内容
16     row=1#定义行
17     for data in all_data:#循环每一行
18         for cow,filed in enumerate(data):#控制列
19             sheet.write(row,cow,filed)
20         row+=1#没写完一行,行数就加1
21     book.save('%s.xls'%table_name)
22 export_excel('app_student')

 

 

 

 

posted on 2018-12-24 12:30  搁浅小夕  阅读(190)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3