python--操作excel

一、写excel模块

1 1 import xlwt
2 2 book = xlwt.Workbook()#新建一个excel
3 3 sheet = book.add_sheet('sheet1')#加sheet页
4 4 sheet.write(0,0,'姓名')#行、列,写入的内容
5 5 sheet.write(0,1,'年龄')
6 6 sheet.write(0,2,'性别')
7 7 book.save('stu.xls')#结尾一定要用.xls

二、读excel模块

 1 import xlrd
 2 book = xlrd.open_workbook('app_student.xls')
 3 sheet = book.sheet_by_index(0)
 4 sheet2 = book.sheet_by_name('shee1')
 5 print(sheet.cell(0,0).value) #指定sheet页里面行和lie获取数据
 6 print(sheet.cell(1,0).value) #指定sheet页里面行和lie获取数据
 7 print(sheet.row_values(0)) #这个获取到第几行的内容
 8 print(sheet.row_values(1)) #这个获取到第几行的内容
 9 print(sheet.nrows) #获取到excel里面总共有多少行
10 print(sheet.ncols)  #总共多少列
11 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中英文的表头修改成中文的

 1 import xlrd
 2 from xlutils import copy
 3 book = xlrd.open_workbook('app_student.xls')
 4 #先用xlrd模块,打开一个excel
 5 new_book = copy.copy(book)
 6 #通过xlutils这个模块里面copy方法,复制一份excel
 7 sheet = new_book.get_sheet(0) #获取sheet页
 8 lis = ['编号','名字','性别','年龄','地址','班级','手机号','金币']
 9 for col,filed in enumerate(lis):#enumerate打印列表下标及元素,循环列表时,下标会自增
10     sheet.write(0,col,filed)
11 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')

 

 

猜你喜欢

转载自www.cnblogs.com/yttbk/p/9020757.html