Python將MySQL的數(shù)據(jù)批量寫(xiě)入 Excel表

演示版本:Python-3.8.5、Mysql-8.0.26、WPS Office 2019

所需模塊:xlwings、pymysql

代碼如下:


import xlwings as xw

import pymysql as? py

#連接數(shù)據(jù)庫(kù)

db = py.connect(host = 'localhost', user = 'root',\

? ? ? ? ? ? ? ? ? password= 'qweiwei123', database= 'mydatabase')

cursor = db.cursor()

app = xw.App(visible = False)

wb = app.books.add()

sheet=wb.sheets.add('customers')

sql="select * from customers"

#獲取數(shù)據(jù)庫(kù)數(shù)據(jù)

cursor.execute(sql)

data = cursor.fetchall()


#獲取表格的字段

table_field = [i[0] for i in cursor.description]

#拼接表格字段和數(shù)據(jù)

data = list(data)

data.insert(0,list(table_field))

#寫(xiě)入數(shù)據(jù)

sheet['A1'].expand('table').value = data



wb.save()

wb.close()

app.quit()

db.close()

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容