python學習筆記-day7-2-【python從mysql資料庫導資料到excel,讀excel,修改excel】

來源:互聯網
上載者:User

標籤:tab   xlrd   第三方庫   串連   inf   SQ   就是   fetch   產生   

這節說下如何用python把資料庫裡的資料匯出到excel裡,並如何讀取excel, 修必excel等操作。

 

一、用python把資料庫裡的資料匯出到excel裡

1、匯入如下的模組,沒有的話需要安裝

import pymysql #mysql串連模組
import xlwt #寫excel的第三方庫

 

從資料庫導資料,寫到excel檔案裡

import pymysql,xlwt

def export_excel(table_name):
import pymysql
host, user, passwd, db = ‘127.0.0.1‘, ‘xxx‘, ‘123456‘, ‘xxxx‘
conn = pymysql.connect(user=user,host=host,port=3306,passwd=passwd,db=db,charset=‘utf8‘)
cur = conn.cursor() # 建立遊標
sql = ‘select * from %s;‘ %table_name
cur.execute(sql) # 執行mysql
fileds = [filed[0] for filed in cur.description] # 列表產生式,所有欄位
all_data = cur.fetchall() #所有資料
#寫excel
book = xlwt.Workbook() #先建立一個book
sheet = book.add_sheet(‘sheet1‘) #建立一個sheet表
# col = 0
# for field in fileds: #寫表頭的
# sheet.write(0, col, field)
# col += 1
#enumerate自動計算下標
for col, field in enumerate(fileds): #跟上面的代碼功能一樣
sheet.write(0, col, field)

#從第一行開始寫
row = 1 #行數
for data in all_data: #二維資料,有多少條資料,控制行數
for col, field in enumerate(data): #控制列數
sheet.write(row, col, field)
row += 1 #每次寫完一行,行數加1
book.save(‘%s.xls‘ %table_name) #儲存excel檔案

export_excel(‘app_student‘)

結果,產生了app_student.xls檔案


二、內建函數enumerate 
# enumerate #自動計算下標
# fileds = [‘id‘, ‘name‘, ‘sex‘, ‘addr‘, ‘gold‘,‘score‘]
# for index, filed in enumerate(fileds): #同時列印下標
# print(index, filed)

 

三、讀excel

 

 四、修改excel

import xlrd
from xlutils import copy #這個模組需要這樣匯入

 

 

五、操作資料庫,excel操作小結

    cur = coon.cursor(cursor=pymysql.cursors.DictCursor)
建立遊標的時候指定了遊標類型,返回的就是一個字典了。
fetchall() #擷取到這個sql執行的全部結果,它把資料庫表裡面的每一行資料放到一個list裡面
[ [‘1‘,‘2‘,‘3‘] ] [{},{},{}]
fetchone() #擷取到這個sql執行的一條結果,它返回就只是一條資料

如果sql語句執行的結果是多條資料的時候,那就用fetchall()
如果你能確定sql執行的結果就只有一條,那麼就用fetchone()

需求:只要你傳入一個表名,就能把所有的資料匯入出來,欄位名是excel的表頭
1、要動態擷取到表的欄位 cur.description能擷取到表的欄位
fileds = [ filed[0] for filed in cur.description ]
2、擷取資料了 select * from "%s" % table_name
3、迴圈寫入excel

enumerate([list,list2]) #迴圈的時候,直接擷取到下標,和值
for index,value in enumerate([list,list2]):
print(index,vlaue)

 

python學習筆記-day7-2-【python從mysql資料庫導資料到excel,讀excel,修改excel】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.