使用python將excel數(shù)據(jù)導入數(shù)據(jù)庫過程詳解
因為需要對數(shù)據(jù)處理,將excel數(shù)據(jù)導入到數(shù)據(jù)庫,記錄一下過程。
使用到的庫:xlrd 和 pymysql (如果需要寫到excel可以使用xlwt)
直接丟代碼,使用python3,注釋比較清楚。
import xlrd import pymysql # import importlib # importlib.reload(sys) #出現(xiàn)呢reload錯誤使用 def open_excel(): try: book = xlrd.open_workbook("XX.xlsx") #文件名,把文件與py文件放在同一目錄下 except: print("open excel file failed!") try: sheet = book.sheet_by_name("sheet名稱") #execl里面的worksheet1 return sheet except: print("locate worksheet in excel failed!") #連接數(shù)據(jù)庫 try: db = pymysql.connect(host="127.0.0.1",user="root", passwd="XXX", db="XXX", charset='utf8') except: print("could not connect to mysql server") def search_count(): cursor = db.cursor() select = "select count(id) from XXXX" #獲取表中xxxxx記錄數(shù) cursor.execute(select) #執(zhí)行sql語句 line_count = cursor.fetchone() print(line_count[0]) def insert_deta(): sheet = open_excel() cursor = db.cursor() for i in range(1, sheet.nrows): #第一行是標題名,對應表中的字段名所以應該從第二行開始,計算機以0開始計數(shù),所以值是1 name = sheet.cell(i,0).value #取第i行第0列 data = sheet.cell(i,1).value#取第i行第1列,下面依次類推 print(name) print(data) value = (name,data) print(value) sql = "INSERT INTO XXX(name,data)VALUES(%s,%s)" cursor.execute(sql,value) #執(zhí)行sql語句 db.commit() cursor.close() #關閉連接 insert_deta() db.close()#關閉數(shù)據(jù) print ("ok ")
XXX里自行修改自己的名稱。
說明:對于不規(guī)則的單元格,例如合并過的單元格會取到空值。
優(yōu)化了一下這個程序
import pymysql import xlrd # 連接數(shù)據(jù)庫 try: db = pymysql.connect(host="127.0.0.1", user="root", passwd="XXX", db="XXX", charset='utf8') except: print("could not connect to mysql server") def open_excel(): try: book = xlrd.open_workbook("XXX.xlsx") #文件名,把文件與py文件放在同一目錄下 except: print("open excel file failed!") try: sheet = book.sheet_by_name("XXX") #execl里面的worksheet1 return sheet except: print("locate worksheet in excel failed!") def insert_deta(): sheet = open_excel() cursor = db.cursor() row_num = sheet.nrows for i in range(1, row_num): # 第一行是標題名,對應表中的字段名所以應該從第二行開始,計算機以0開始計數(shù),所以值是1 row_data = sheet.row_values(i) value = (row_data[0],row_data[1],row_data[2],row_data[3]) print(i) sql = "INSERT INTO demo_yangben(xxx,xxxx,xxxx,xxxx)VALUES(%s,%s,%s,%s)" cursor.execute(sql, value) # 執(zhí)行sql語句 db.commit() cursor.close() # 關閉連接 open_excel() insert_deta()
再改一下,每一萬條數(shù)據(jù)寫入到數(shù)據(jù)庫一次
import pymysql import xlrd import sys ''' 連接數(shù)據(jù)庫 args:db_name(數(shù)據(jù)庫名稱) returns:db ''' def mysql_link(de_name): try: db = pymysql.connect(host="127.0.0.1", user="xxx", passwd="xxx", db=xxx, charset='utf8') return db except: print("could not connect to mysql server") ''' 讀取excel函數(shù) args:excel_file(excel文件,目錄在py文件同目錄) returns:book ''' def open_excel(excel_file): try: book = xlrd.open_workbook(excel_file) # 文件名,把文件與py文件放在同一目錄下 print(sys.getsizeof(book)) return book except: print("open excel file failed!") ''' 執(zhí)行插入操作 args:db_name(數(shù)據(jù)庫名稱) table_name(表名稱) excel_file(excel文件名,把文件與py文件放在同一目錄下) ''' def store_to(db_name, table_name, excel_file): db = mysql_link(db_name) # 打開數(shù)據(jù)庫連接 cursor = db.cursor() # 使用 cursor() 方法創(chuàng)建一個游標對象 cursor book = open_excel(excel_file) # 打開excel文件 sheets = book.sheet_names() # 獲取所有sheet表名 for sheet in sheets: sh = book.sheet_by_name(sheet) # 打開每一張表 row_num = sh.nrows print(row_num) list = [] # 定義列表用來存放數(shù)據(jù) num = 0 # 用來控制每次插入的數(shù)量 for i in range(1, row_num): # 第一行是標題名,對應表中的字段名所以應該從第二行開始,計算機以0開始計數(shù),所以值是1 row_data = sh.row_values(i) # 按行獲取excel的值 value = (row_data[0], row_data[1], row_data[2], row_data[3], row_data[4], row_data[5], \ row_data[6], row_data[7], row_data[8], row_data[9], row_data[10], row_data[11], row_data[12], row_data[13], row_data[14]) list.append(value) # 將數(shù)據(jù)暫存在列表 num += 1 if( num>= 10000 ): # 每一萬條數(shù)據(jù)執(zhí)行一次插入 print(sys.getsizeof(list)) sql = "INSERT INTO " + table_name + " (time, xingbie, afdd, xzb, yzb, cfbj, jjlbmc, \ bjlbmc, bjlxmc, bjlxxlmc, gxqymc,gxdwmc, afql, afxqxx, cjdwmc)\ VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" cursor.executemany(sql, list) # 執(zhí)行sql語句 num = 0 # 計數(shù)歸零 list.clear() # 清空list print("worksheets: " + sheet + " has been inserted 10000 datas!") print("worksheets: " + sheet + " has been inserted " + str(row_num) + " datas!") db.commit() # 提交 cursor.close() # 關閉連接 db.close() if __name__ == '__main__': store_to('demo', 'demo_yangben', 'xxx.xlsx')
思考,如果數(shù)據(jù)插入有錯誤,怎么解決,
其實有很多數(shù)據(jù)庫工具可以直接來解決這個問題,注意字符轉換的格式就好。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
python如何實現(xiàn)MK突變檢驗方法,代碼復制修改可用
這篇文章主要介紹了python如何實現(xiàn)MK突變檢驗方法,代碼復制修改可用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05django下創(chuàng)建多個app并設置urls方法
在本篇文章里小編給大家分享的是一篇關于django下創(chuàng)建多個app并設置urls方法,需要的朋友們可以參考學習下。2020-08-08NumPy對數(shù)組按索引查詢實戰(zhàn)方法總結
數(shù)組的高級操作主要是組合數(shù)組,拆分數(shù)組,tile數(shù)組和重組元素,下面這篇文章主要給大家介紹了關于NumPy對數(shù)組按索引查詢的相關資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2022-08-08python3 設置多進程名稱并在ps命令中可見(Centos7 系統(tǒng))
setproctitle 是一個 Python 模塊,用于設置進程標題(process title),通過設置進程標題,可以讓進程在系統(tǒng)級的進程管理工具中展示自定義的名稱,方便用戶查看和管理進程,本文介紹python3 設置多進程名稱并在ps命令中可見,感興趣的朋友一起看看吧2024-03-03Python循環(huán)語句之break與continue的用法
這篇文章主要介紹了Python循環(huán)語句之break與continue的用法,是Python入門學習中的基礎知識,需要的朋友可以參考下2015-10-10