一、導入相關的包
import pymysql
import xlsxwriter
import time
二、創建excel並連接數據庫
#創建excel表
now_time = time.strftime("%Y_%m_%d_%H")
persons_excel = xlsxwriter.Workbook(r"./report/"+ now_time + "persondata.xlsx")
sheet = persons_excel.add_worksheet("sheet")
#連接mysql
db = pymysql.connect("localhost","root","123456","test")
cursor = db.cursor()
sql = "select * from persons"
rows = cursor.execute(sql)
alldata = cursor.fetchall()#展示表中所有數據
row = len(alldata)#獲取表的行數
三、代碼部分
1、先獲取表頭,寫入excel第1行
header = cursor.description
table_header = []
for i in header:
table_header.append(i[0])
sheet.write_row(0,0,table_header)#把表頭寫進去
2、寫入數據的函數,按行寫入
k = 0
def write_data(data):
global k
k = k + 1
sheet.write_row(k,0,data)
3、調用函數
for i in alldata:
write_data(i)
4、關閉excel,必須有關閉這一步,否則excel無法保存
persons_excel.close()
ps:初學相關技術,有不對之處歡迎糾正!