Python實現(xiàn)SqlServer查詢結果并寫入多個Sheet頁的方法詳解
1、引言
小絲:魚哥,我想請教一個問題。
小魚:國慶假期你經(jīng)歷了什么,讓你變得如此的 “善良”?
小絲:別這么說,我一直很善良,至少,很正直…
小魚:打住,直接點, 你有什么需要幫助的?
小絲:我就是想把查詢的結果也入到excel表中
小魚:然后呢?
小絲:sqlserver數(shù)據(jù)庫。
小魚:…好吧,還有其他要求嗎?
小絲:沒有了。
小魚:OK,我就花費幾分鐘,給你整一個。
2、代碼實戰(zhàn)
2.1 openpyxl寫入excel
2.1.1 安裝
凡是涉及第三方庫,必須需要安裝,
老規(guī)矩,直接pip安裝
pip install openpyxl pip install pymssql
其它安裝方式,直接看這兩篇:
《Python3,選擇Python自動安裝第三方庫,從此跟pip說拜拜?。 ?/a>
《Python3:我低調(diào)的只用一行代碼,就導入Python所有庫!》
2.1.2 代碼
代碼示例
# -*- coding:utf-8 -*- # @Time : 2022-10-10 # @Author : Carl_DJ ''' 實現(xiàn)功能: 1、python直接鏈接sqlserver數(shù)據(jù)庫,讀取數(shù)據(jù)庫內(nèi)容 2、執(zhí)行 查詢結果,并寫入到excel表中 應用模塊: pymssql,os,openpyxl ''' import os import pymysql #mysql數(shù)據(jù)庫鏈接 import pymssql #sqlserver數(shù)據(jù)庫鏈接 import openpyxl #輸出文件夾 outfile_path = './data' #如果沒有outfile_path 這個文件夾,就自動創(chuàng)建 if not os.path.exists(outfile_path): os.mkdir(outfile_path) #輸出文件名稱 filename = r'SQLtest.xlsx' file_path= os.path.join(outfile_path,old_filename) #創(chuàng)建數(shù)據(jù)庫鏈接 #鏈接SqlServer conn = pymssql.connect(host = "localhost", port = 3306, user = "", psd = "", database = "") if conn: print("數(shù)據(jù)庫鏈接成功") time.sleep(3) #sql查詢語句 sql = "select UUID,KEYID,TYPE,NAME,PRICE from KEY_INFO WHERE NAME LIKE '%測試商品名稱'" #創(chuàng)建游標 cur = conn.cursor() #執(zhí)行sql語句 cur.execute(sql) #返回查詢結果 result = cur.fetchall() #創(chuàng)建一個工作簿對象 wb = openpyxl.Workbook() #定義sheet名 Key_Info_sheet = wb.create_sheet('KEY_INFO ',0) #獲取默認sheet頁 # Key_Info_sheet = book.active #獲取表頭信息 h1 = [filed[0] for filed in cur.description] Key_Info_sheet.append(h1) for i in result: Key_Info_sheet.append(i) wb.save(file_path) # 關閉數(shù)據(jù)庫鏈接 cur.close() conn.close()
執(zhí)行結果
嗯,這就非常完美的寫入excel了。
2.2 pandas寫入excel
小絲:魚哥,我這一次要執(zhí)行多個SQL語句,
小魚:… 你不是說沒有了嗎
小絲:突然想起來的。
小魚:好吧,還有其他的要求嗎?
小絲:然后把每個SQL查詢結果寫入不同的sheet頁
小魚:xxxxxx??!還有嗎????!?。?/p>
小絲:沒有了。
小魚:有也沒有。
關于小絲提的要求, 我換一個寫法,畢竟,多學幾個知(姿 )識(勢 ),百利而無一害。
2.2.1 安裝
這次有pandas來寫。
所以,第一步,安裝
pip install pandas
其它安裝方式,直接看這兩篇:
《Python3,選擇Python自動安裝第三方庫,從此跟pip說拜拜!!》
《Python3:我低調(diào)的只用一行代碼,就導入Python所有庫!》
2.2.2 代碼
sql文檔
代碼示例
# -*- coding:utf-8 -*- # @Time : 2022-10-10 # @Author : Carl_DJ ''' 實現(xiàn)功能: 1、python直接鏈接SqlServer數(shù)據(jù)庫,實現(xiàn)SQL查詢 2、同時執(zhí)行多條sql語句,查詢結果分別寫入不同的sheet頁中; 應用模塊: pandas,pymssql,os,time ''' import pandas as pd from pandas.io import sql import pymssql import time,os #設置時間戳 now = time.strftime("%Y_%m_%d-%H%M%S",time.localtime()) print(f'執(zhí)行時間:{now}') #創(chuàng)建數(shù)據(jù)庫鏈接 #鏈接SqlServer conn = pymssql.connect(host = "localhost", port = 3306, user = "", psd = "", database = "") if conn: print("數(shù)據(jù)庫鏈接成功") time.sleep(3) #輸出文件夾 file_path = './data' #如果沒有outfile_path 這個文件夾,就自動創(chuàng)建 if not os.path.exists(file_path): os.mkdir(file_path) #輸出文件格式 Outfile_name = ( 'SqlsTest' + now + '.xlsx') #讀取sql文件名稱 sqls_name = r'SqlsFile.txt' #sql執(zhí)行腳本文件(參數(shù)化路徑) MCsql_file = os.path.join(file_path,MCsql_name) #輸出文件夾路徑 Outfile_path = os.path.join(file_path,Outfile_name) #把查詢結果寫入不同的sheet頁,對sheet頁進行命名 sheet_names = ['KEY_INFO','PRO_INFO'] #定義讀取sql方法,返回sql語句 def sqls(MCsql_file): global sqlstrs with open(MCsql_file,'r',encoding='utf-8') as f: #每個sql之間,以“;”作為分隔符 sqlstrs = f.read().split(';') #定義數(shù)據(jù)查詢方法 def quert_method(sql_str): #設置全局變量 global df df = pd.read_sql(sql_str,con=conn) #執(zhí)行程序 if __name__ == '__main__': sqls(MCsql_file) #寫入excel文件 with pd.ExcelWriter(Outfile_path) as writer: for i in range(0,len(sqlstrs)): quert_method(sqlstrs[i]) df.to_excel(writer,sheet_name=sheet_names[i],index=False,header=True) print("數(shù)據(jù)寫入完成!") # 關閉數(shù)據(jù)庫鏈接 conn.close() print("數(shù)據(jù)庫鏈接關閉!")
執(zhí)行結果
3、總結
看到這里,今天的分享差不多就完成了。
今天主要通過鏈接SqlServer數(shù)據(jù)庫,把查詢數(shù)據(jù)結果寫入到excel表中。
同時,應用openpyxl 和pandas兩個模塊,分別對excel的操作。
到此這篇關于Python實現(xiàn)SqlServer查詢結果并寫入多個Sheet頁的方法詳解的文章就介紹到這了,更多相關Python寫入多個Sheet頁內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
研究Python的ORM框架中的SQLAlchemy庫的映射關系
這篇文章主要介紹了研究Python的ORM框架中的SQLAlchemy庫的映射關系,SQLAlchemy庫是一個常見的Python中操作數(shù)據(jù)庫的工具,需要的朋友可以參考下2015-04-04python實現(xiàn)將中文日期轉換為數(shù)字日期
這篇文章主要介紹了python實現(xiàn)將中文日期轉換為數(shù)字日期,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07python3 循環(huán)讀取excel文件并寫入json操作
這篇文章主要介紹了python3 循環(huán)讀取excel文件并寫入json操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07詳解使用Python寫一個向數(shù)據(jù)庫填充數(shù)據(jù)的小工具(推薦)
這篇文章主要介紹了用Python寫一個向數(shù)據(jù)庫填充數(shù)據(jù)的小工具,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09python實現(xiàn)數(shù)通設備端口監(jiān)控示例
這篇文章主要介紹了python實現(xiàn)數(shù)通設備端口監(jiān)控示例,需要的朋友可以參考下2014-04-04對pandas中時間窗函數(shù)rolling的使用詳解
今天小編就為大家分享一篇對pandas中時間窗函數(shù)rolling的使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11