演示版本: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()