1. 程式人生 > 實用技巧 >基於python的通過sql自動生成excel資料

基於python的通過sql自動生成excel資料

好久不更新 了... 今天來寫一個 sql轉換成excel的工具; 目的是給哪些linux使用者使用此類工具!

且看原始碼:

import pymysql
import xlwt
import operator
'''
__author__ =rianley
__blog__ = https://www.cnblogs.com/rianley

'''
'sql匯出excel方法'
def toExcel(host,port,user,passwd,db,charset,sql,sheet_name,out_path):
    db = pymysql.connect(
        host
=host, port=port, user=user, passwd=passwd, db=db, charset=charset ) cursor = db.cursor() count = cursor.execute(sql) print("查詢出" + str(count) + "條記錄") # 來重置遊標的位置 cursor.scroll(0, mode='absolute') # 搜取所有結果 results = cursor.fetchall()
# 獲取MYSQL裡面的資料欄位名稱 fields = cursor.description workbook = xlwt.Workbook() # workbook是sheet賴以生存的載體。 sheet = workbook.add_sheet(sheet_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)): if results[row-1][col] is None: sheet.write(row, col, u'%s' % '') else: sheet.write(row, col, u'%s' % results[row - 1][col]) workbook.save(out_path) if __name__ == '__main__': host = "127.0.0.1" port = 3306 user = 'root' passwd = "123456" db = "test" charset = "utf8" print("mysql連線是否使用預設配置?y/n") choose = input() if operator.eq('n',choose) or operator.eq('n',choose): print("host:") host = input() print("port:") port = input() print("userName:") user = input() print("passWord:") passwd = input() print("databaseName:") db = input() print("請輸入Excel表格名稱:") sheet_name = input() print("請貼上您的SQL相對檔案路徑:") sql_path = input() with open(sql_path,'r',encoding='utf8')as f: sql=f.read() print("儲存的路徑") file_path=input() out_path = r''+file_path+'/'+sheet_name+'.xls' print('輸入路徑為',out_path) toExcel(host,port,user,passwd,db,charset,sql,sheet_name,out_path) print("匯出成功您的檔案位置為:",out_path)