首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >使用Python从 MySQL写数据到E

使用Python从 MySQL写数据到E

作者头像
py3study
发布2020-01-06 18:01:21
发布2020-01-06 18:01:21
1.5K0
举报
文章被收录于专栏:python3python3

直接上代码:

代码语言:javascript
复制
#!/usr/bin/env python
#coding:utf-8

import xlwt
import MySQLdb
import datetime

database = MySQLdb.connect(host='192.168.1.30',user='root',passwd='123456',db='crm')
#设置字符集
database.set_character_set('utf8')
cursor = database.cursor()
cursor.execute('SET NAMES utf8;') 
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_connection=utf8;')

starttime = datetime.datetime.now()
print '开始时间:%s' % (starttime)

#通过SQL得到该表有多少行,如果想取出指定的数据,只需要在后面加where条件即可。
sql2 = 'select count(*) from bill_test;';
cursor.execute(sql2)
count_rows=cursor.fetchone()[0]

wbk = xlwt.Workbook(encoding='utf-8',style_compression=0)
sheet = wbk.add_sheet('sheet 1', cell_overwrite_ok=True)
#设置写excel的样式
style = xlwt.XFStyle()
font = xlwt.Font()
font.name = 'Times New Roman'
#0x0190设置字体为20,默认为0x00C8 字体为10 ,0x00C8为十六进制的数字
font.height = 0x0190
font.bold = True
style.font = font
#查询得到该表有多少列
query_colums="select count(*) from information_schema.COLUMNS where TABLE_SCHEMA='crm' and table_name='bill_test';"
cursor.execute(query_colums)
count_cols = cursor.fetchone()[0]

sql = 'select member_id, name, tel, phone, dq_datetime, address, parking from bill_test;'
cursor.execute(sql)

#定义所有的列名,共7列
columnName = ['账号','名称','电话','手机','到期日期','地址','园区名称']  
#将列名插入表格,共7列
for i in range(len(columnName)):         
        sheet.write(0,i,columnName[i],style)

#通过循环取出每一行数据,写入excel    
for i in range(1,count_rows-1):
    data = cursor.fetchone()
    for j in range(0,count_cols-1):
        sheet.write(i,j,data[j],style)       
cursor.close()
database.close()
wbk.save('C:\Users\XUWU\Desktop\data01.xls')   

endtime=datetime.datetime.now()
print '结束时间:%s' % (endtime)
print '用时:%s 秒' % (endtime-starttime)

执行情况:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档