1. 程式人生 > >Python實現數據庫一鍵導出為Excel表格-----轉載

Python實現數據庫一鍵導出為Excel表格-----轉載

ber field 錯誤 數據庫操作 不成功 html 生存 mysqldb tle

    • 依賴
      • Python2711
      • xlwt
      • MySQLdb
    • 數據庫相關
      • 連接
      • 獲取字段信息
      • 獲取數據
    • Excel基礎
      • workbook
      • sheet
    • 案例
    • 封裝
      • 封裝之後
      • 測試結果
    • 總結

數據庫數據導出為excel表格,也可以說是一個很常用的功能了。畢竟不是任何人都懂數據庫操作語句的。
下面先來看看完成的效果吧。

  • 數據源

技術分享圖片

  • 導出結果
    技術分享圖片

依賴

由於是Python實現的,所以需要有Python環境的支持

Python2.7.11

我的Python環境是2.7.11。雖然你用的可能是3.5版本,但是思想是一致的。

xlwt

pip install xlwt

MySQLdb

pip install MySQLdb
如果上述方式不成功的話,可以到sourceforge官網上去下載windows上的msi版本或者使用源碼自行編譯。

數據庫相關

本次試驗,數據庫相關的其實也就是如何使用Python操作數據庫而已,知識點也很少,下述為我們本次用到的一些簡單的語句。

連接

conn = MySQLdb.connect(host=’localhost’,user=’root’,passwd=’mysql’,db=’test’,charset=’utf8’)

這裏值得我們一提的就是最後一個參數的使用,不然從數據庫中取出的數據就會使亂碼。關於亂碼問題,如果還有不明白的地方,不妨看下這篇文章http://blog.csdn.net/marksinoberg/article/details/52254401。

獲取字段信息

fields = cursor.description

至於cursor,是我們操作數據庫的核心。遊標的特點就是一旦遍歷過該條數據,便不可返回。但是我們也可以手動的改變其位置。

cursor.scroll(0,mode=’absolute’)來重置遊標的位置

獲取數據

獲取數據簡直更是輕而易舉,但是我們必須在心裏明白,數據項是一個類似於二維數組的存在。我們獲取每一個cell項的時候應該註意。

results = cursor.fetchall()

Excel基礎

同樣,這裏講解的也是如何使用Python來操作excel數據。

workbook

工作薄的概念我們必須要明確,其是我們工作的基礎。與下文的sheet相對應,workbook是sheet賴以生存的載體。

workbook = xlwt.Workbook()

sheet

我們所有的操作,都是在sheet上進行的。

sheet = workbook.add_sheet(‘table_message’,cell_overwrite_ok=True)

對於workbook 和sheet,如果對此有點模糊。不妨這樣進行假設。

日常生活中記賬的時候,我們都會有一個賬本,這就是workbook。而我們記賬則是記錄在一張張的表格上面,這些表格就是我們看到的sheet。一個賬本上可以有很多個表格,也可以只是一個表格。這樣就很容易理解了吧。 :-)

案例

下面看一個小案例。

# coding:utf8
import sys

reload(sys)
sys.setdefaultencoding(‘utf8‘)
#    __author__ = ‘郭 璞‘
#    __date__ = ‘2016/8/20‘
#    __Desc__ = 從數據庫中導出數據到excel數據表中

import xlwt
import MySQLdb

conn = MySQLdb.connect(‘localhost‘,‘root‘,‘mysql‘,‘test‘,charset=‘utf8‘)
cursor = conn.cursor()

count = cursor.execute(‘select * from message‘)
print count
# 重置遊標的位置
cursor.scroll(0,mode=‘absolute‘)
# 搜取所有結果
results = cursor.fetchall()

# 獲取MYSQL裏面的數據字段名稱
fields = cursor.description
workbook = xlwt.Workbook()
sheet = workbook.add_sheet(‘table_message‘,cell_overwrite_ok=True)

# 寫上字段信息
for field in range(0,len(fields)):
    sheet.write(0,field,fields[field][0])

# 獲取並寫入數據段信息
row = 1
col = 0
for row in range(1,len(results)+1):
    for col in range(0,len(fields)):
        sheet.write(row,col,u‘%s‘%results[row-1][col])

workbook.save(r‘./readout.xlsx‘)

封裝

為了使用上的方便,現將其封裝成一個容易調用的函數。

封裝之後

# coding:utf8
import sys

reload(sys)
sys.setdefaultencoding(‘utf8‘)
#    __author__ = ‘郭 璞‘
#    __date__ = ‘2016/8/20‘
#    __Desc__ = 從數據庫中導出數據到excel數據表中

import xlwt
import MySQLdb

def export(host,user,password,dbname,table_name,outputpath):
    conn = MySQLdb.connect(host,user,password,dbname,charset=‘utf8‘)
    cursor = conn.cursor()

    count = cursor.execute(‘select * from ‘+table_name)
    print count
    # 重置遊標的位置
    cursor.scroll(0,mode=‘absolute‘)
    # 搜取所有結果
    results = cursor.fetchall()

    # 獲取MYSQL裏面的數據字段名稱
    fields = cursor.description
    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet(‘table_‘+table_name,cell_overwrite_ok=True)

    # 寫上字段信息
    for field in range(0,len(fields)):
        sheet.write(0,field,fields[field][0])

    # 獲取並寫入數據段信息
    row = 1
    col = 0
    for row in range(1,len(results)+1):
        for col in range(0,len(fields)):
            sheet.write(row,col,u‘%s‘%results[row-1][col])

    workbook.save(outputpath)


# 結果測試
if __name__ == "__main__":
    export(‘localhost‘,‘root‘,‘mysql‘,‘test‘,‘datetest‘,r‘datetest.xlsx‘)

import xlwt
import pymysql,string

def export(host,user,password,dbname,table_name,outputpath):
conn = pymysql.connect(host,user,password,dbname,charset=‘utf8‘)
cursor = conn.cursor()

count = cursor.execute(‘select * from ‘+table_name)
print(‘count:‘,count)
# 重置遊標的位置
cursor.scroll(0,mode=‘absolute‘)
# 搜取所有結果
results = cursor.fetchall()

# 獲取MYSQL裏面的數據字段名稱
fields = cursor.description
workbook = xlwt.Workbook()
sheet = workbook.add_sheet(‘table_‘+table_name,cell_overwrite_ok=True)

# 寫上字段信息
for field in range(0,len(fields)):
sheet.write(0,field,fields[field][0])

# 獲取並寫入數據段信息
row = 1
col = 0


for row in range(1,len(results)+1):
for col in range(0,len(fields)):
sheet.write(row,col,u‘%s‘%results[row-1][col])

workbook.save(outputpath)


# 結果測試
if __name__ == "__main__":
export(‘118.24.3.40‘,‘jxz‘,‘123456‘,‘jxz‘,‘app_student‘,‘app_student.xls‘)


import yagmail
#賬號 密碼 郵箱服務器 收件人 抄送 主題 正文 附件

username=‘[email protected]
passwd=‘Admin12345‘ #郵箱的授權密碼 ,#SMTP授權碼 #535錯誤,AUTH錯誤,基本上是授權碼錯誤
mail=yagmail.SMTP(user=username,password=passwd,host=‘smtp.163.com‘) #QQ郵箱要加這個參數,連接上郵箱了 #smtp_ssl=True 安全協議,,163不需要

# mail.send(to=‘[email protected]‘,cc=‘[email protected]‘,subject=‘開會123‘,contents=‘上午9點開會123‘) # 發送、抄送給一人
mail.send(to=[‘[email protected]‘,‘[email protected]‘,‘[email protected]‘,‘[email protected]‘], # 發送給多人,to傳list(win10路徑寫\\)
cc=[‘[email protected]‘,‘[email protected]‘],
subject=‘app_student導出‘,
contents=‘app_student導出20:08‘,
attachments=r‘G:\\python-DownLoad\\練習code\\day6\\day6-作業\\app_student.xls‘)

測試結果

id  name    date
1   dlut    2016-07-06
2   清華大學    2016-07-03
3   北京大學    2016-07-28
4   Mark    2016-08-20
5   Tom 2016-08-19
6   Jane    2016-08-21

總結

回顧一下,本次試驗用到了哪些知識點。

  • Python簡易操作數據庫
  • Python簡易操作Excel
  • 數據庫取出數據亂碼問題解決之添加charset=utf-8
  • 以二維數組的角度來處理獲取到的結果集。

Python實現數據庫一鍵導出為Excel表格-----轉載