基於python的通過sql自動生成excel數據


 

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

且看源碼

import operator
import pymysq
import xlwt
''' __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=int(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'
# 防止輸入//不被系統識別
out_path = out_path.replace('//','/')
    print('輸入路徑為',out_path) toExcel(host,port,user,passwd,db,charset,sql,sheet_name,out_path) print("導出成功您的文件位置為:",out_path)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM