python mysql导出到excel_Python实现mysql中数据导成excel表格

这篇博客介绍了如何使用Python将MySQL数据库中的数据转换并保存为Excel表格。支持中文数据转换,日期格式可自定义,例如默认格式为'YYYY-MM-DD hh:mm:ss'。目前代码仅在Windows平台上测试通过,Linux平台可能需要调整编码设置。
摘要由CSDN通过智能技术生成

V1.0 [infobg class="warning" closebtn="" color="" bgcolor=""] 1、支持中文数据转换,此处数据库等信息均使用utf-8。 2、日期格式可自定义(对于东代码的朋友来说),默认格式:2015-04-21 20:31:21 3、目前仅实现了创建新表功能,同一表名会覆盖原表。 4、目前仅在windows平台测试过,linux平台可能需要修改下编码。

84533dc12e905272fbe20feeb9a515d1.png [/infobg] [toggle hide="yes" title="Python代码" color=""]

# Create your views here.

# -*- coding: utf-8 -*-

import MySQLdb

import xlwt

from datetime import datetime

wbk=xlwt.Workbook(encoding='utf-8')

sheet=wbk.add_sheet('sheet 2')

sheet.write(0,0,'Uid')

sheet.write(0,1,u'姓名')

sheet.write(0,2,'password')

sheet.write(0,3,'Email')

sheet.write(0,4,'Date')

row=1

fmt='YYYY-MM-DD hh:mm:ss'

try:

conn=MySQLdb.connect(host="localhost",user='root',passwd="",db="personalblog_db",charset='utf8')

cur=conn.cursor()

count=cur.execute('select * from users')

print 'there has %s rows record' % count

results=cur.fetchmany(count)

for uid,uname,upassword,uemail,udate in results:

sheet.write(row,0,uid)

sheet.write(row,1,uname)

sheet.write(row,2,upassword)

sheet.write(row,3,uemail)

style = xlwt.XFStyle()

style.num_format_str = fmt

sheet.write(row,4,udate,style)

row+=1

wbk.save('users1.xls')

cur.close()

conn.commit()

conn.close()

except MySQLdb.Error,e:

print "Mysql Error %d: %s"%(e.args[0],e.args[1]) [/toggle]

本文同步分享在 博客“蜜汁炒酸奶”(other)。

如有侵权,请联系 support@oschina.cn 删除。

本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值