批量向mysql匯入資料夾中的excl檔案
阿新 • • 發佈:2018-12-24
因為需要批量的匯入一批不包括表到資料庫中,用手工太繁瑣,所以寫點程式批量匯入,但是這個是單程序的,有想改進的小夥伴可以改成多程序的(可能快很多)
import pymysql from xlrd import xldate_as_tuple import xlrd from datetime import datetime import os, time, random ''' 輸入資料庫的名字和資料表的名字,然後選擇合適的資料夾,之後批量的把資料夾中的excl表中的資料匯入到同一個資料表中。 這個需要提前做的工作是:1、提前在資料庫中建立資料表,2、再插入的資料的到時候同樣需要 填寫 需要插入 欄位的名字 和 欄位的資料型別3、需要插入的資料夾的名字 4、資料庫和資料表的名字 ''' def mysql_link(de_name): try: db = pymysql.connect(host="192.168.0.125", user="zhoujianhui", passwd="root", db='test', charset='utf8') return db except: print("could not connect to mysql server") ''' 讀取excel函式 args:excel_file(excel檔案,目錄在py檔案同目錄) returns:book ''' ''' 執行插入操作 args:db_name(資料庫名稱) table_name(表名稱) excel_file(excel檔名,把檔案與py檔案放在同一目錄下) ''' def store_to(db_name, table_name, Folder_file_total): db = mysql_link(db_name) # 開啟資料庫連線 cursor = db.cursor() # 使用 cursor() 方法建立一個遊標物件 cursor for Folder_file in [a for a, b, c in os.walk(Folder_file_total, topdown=True)][1:]: excel_files = sorted(os.listdir(Folder_file),key=lambda x:int(x[:-5])) excel_files = [Folder_file + '\\' + i for i in excel_files] print(excel_files) for excel_file in excel_files: start = time.time() book = xlrd.open_workbook(excel_file) # 開啟excel檔案 sheets = book.sheet_names() # 獲取所有sheet表名 sh = book.sheet_by_name(sheets[0]) row_num = sh.nrows # 獲取行數 print(excel_file) print(row_num) list = [] # 定義列表用來存放資料 for i in range(1, row_num): # 第一行是標題名,對應表中的欄位名所以應該從第二行開始,計算機以0開始計數,所以值是1 row_data = sh.row_values(i) # 按行獲取excel的值 row_data[1] = datetime(*xldate_as_tuple(row_data[1], 0)).strftime( '%Y/%m/%d') # 將excl中提取的數字時間格式格式轉化成正常的時間格式 value = tuple(row_data) list.append(value) # 將資料暫存在列表 sql = "INSERT INTO " + table_name + "(裝置ID,日期,地理城市,運營城市名,區縣,網點ID,網點名,裝置型別,首次啟用時間, 排班值守, 主櫃數, 副櫃數, 箱格數, 大箱格數, 中箱格數, 小箱格數, 投件量_大箱, 投件量_中箱格, 投件量_小箱格, 取件量_付費取件, 投件量, 投件率_大箱, 投件率_中箱格, 投件率_小箱格, 投件率, 滯留件數量_96小時, 取件免費時長,取件基礎費用, 取件基礎費用時長, 取件超時續費單價, 取件超時續費週期, 取件費用封頂價格)VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" print('準備匯入...') cursor.executemany(sql, list) # 執行sql語句 db.commit() # 提交 list.clear() # 清空list end = time.time() print("excl: " + excel_file + " has been inserted " + str(row_num) + " datas!") print("excl: " + excel_file + " has been costed %s s" % (end - start)) print('There is a total %d has been imported %d 個表,Completion degree %d%%' % ( len(excel_files), (excel_files.index(excel_file) + 1), (excel_files.index(excel_file) + 1) * 100 / len(excel_files))) cursor.close() # 關閉連線 db.close() if __name__ == '__main__': first = time.time() store_to('test','裝置大表1_2018',r'C:\Users\lenovo\Desktop\裝置大表3') last = time.time() print('這件事共用時 %f h'% round((last-first)/3600,2))