码迷,mamicode.com
首页 > 编程语言 > 详细

新手学习python(十一)读 / 修改 / 导出excel

时间:2018-06-18 18:27:15      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:下标   student   文档   exp   pymysql   work   rate   导出   自动   

1)读excel,使用xlrd模块

import xlrd
book =xlrd.open_workbook(‘app_student.xls‘)
sheet=book.sheet_by_index(0) #根据顺序获取的
# sheet2=book.sheet_by_name(‘sheet1‘) #也可根据名字获取
# print(sheet.cell(0,0).value) #指定sheet页里面行和列获取数据
# print(sheet.row_values(0)) #获取到第几行的内容
# print(sheet.nrows) #获取到excel里面总共有多少行
for i in range(sheet.nrows): #循环获取到每行数据
print(sheet.row_values(i))
print(sheet.ncols) #总共多少列


2)修改excel,使用xrld模块
import xlrd
from xlutils import copy #导入xlutils模块里的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=[‘编号‘,‘姓名‘,‘性别‘,‘年龄‘,‘地址‘,‘班级‘,‘手机号‘,‘金币‘,]
col=0
for i in lis: #把list里的值写入excel的0行(从0开始计数)
sheet.write(0,col,i)
col +=1
new_book.save(‘app_student.xls‘) #再把新excel命名为之前文档的名字


3)通用导出excel,使用xlwt模块
import pymysql,xlwt
def export_excel(table_name):
host,user,passwd,db=‘xx.xx.xx.xx‘,‘aaa‘,‘123456‘,‘aaa‘ #pymysql的信息
coon = pymysql.connect(
host=host, user=user, passwd=passwd,
port=3306, db=db, charset=‘utf8‘ # port必须写int类型,charset必须写utf8
)

cur = coon.cursor() # 建立游标
sql=‘select * from %s;‘%table_name
cur.execute(sql) #执行sql语句
fileds=[filed[0] for filed in cur.description] #表头所有的字段
print(fileds)
all_data=cur.fetchall() #获取数据返回的所有数据
book=xlwt.Workbook() #创建一个excel
sheet=book.add_sheet(‘sheet1‘) #新增一个sheet

for col,filed in enumerate(fileds): #把表头字段写入sheet的0行
sheet.write(0,col,filed)
#print(all_data)
row=1 #定义一个变量,控制行
for data in all_data: #控制行
for col, filed in enumerate(data): #控制列,enumerate自动取下标,加1
sheet.write(row, col, filed) #行不变,变换列,依次写入数据
row +=1 #向下移动行数

book.save(‘%s.xls‘%table_name) #保存表格

export_excel(‘app_student‘) #导出表格


新手学习python(十一)读 / 修改 / 导出excel

标签:下标   student   文档   exp   pymysql   work   rate   导出   自动   

原文地址:https://www.cnblogs.com/bainbian1234/p/9190635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!