首先安裝xlrd模塊:pip install xlrd ,核心代碼網上有很多,這里主要是關於一些個人實際碰到問題細節的處理
1、excel數據不規范導致讀取的數據存在空白行和列;
2、參數化執行sql
代碼如下,僅供參考:
1 import xlrd 2 3 import AppSetting.AppConfig as config 4 import AppSetting.dbConfig as db 5 6 # 處理excel依賴xlrd模塊 pip install xlrd 7 8 # 讀取excel文件 9 excel_data = xlrd.open_workbook(config.file_path) 10 # 獲取第一個sheet頁 11 sheet = excel_data.sheet_by_index(0) 12 # 總行數 13 rows = sheet.nrows 14 # 獲取列(經常讀取到的excel可能存在空白行或者空白列,這里根據第一行的數據獲取要導入的數據的列數) 15 rowlsts = [i for i in sheet.row_values(0) if i != ''] 16 cursor = db.connect.cursor() 17 # 定義變量n,當n=0 時組裝參數化的sql 18 n = 0 19 sql = "" 20 # 由於excel中第一行存儲的是字段名,獲取數據從第二行開始 21 for i in range(1, rows): 22 try: 23 item = sheet.row_values(i)[:len(rowlsts)] 24 data = '' 25 # 組裝參數化sql,通過拼接%s得到占位符 26 for j in range(0, len(rowlsts)): 27 data += "%s," 28 data = data.rstrip(',') 29 if n == 0: 30 sql = "insert into co_zfxx(%s) values( %s )" % (str.join(',', rowlsts), data) 31 cursor.execute(sql, tuple(item)) 32 else: 33 cursor.execute(sql, tuple(item)) 34 35 except Exception as ex: 36 print(ex) 37 38 finally: 39 n += 1 40 41 db.connect.commit() 42 cursor.close() 43 db.connect.close()
本次測試執行5w條數據(26個字段),執行時間22s