Python實現mysql中數據導成excel表格

V1.0

1、支持中文數據轉換,此處數據庫等信息均使用utf-8。

2、日期格式可自定義(對於東代碼的朋友來說),默認格式:2015-04-21 20:31:21

3、目前僅實現了創建新表功能,同一表名會覆蓋原表。

4、目前僅在windows平臺測試過,linux平臺可能需要修改下編碼。

Python代碼

# 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])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章