生活随笔
收集整理的這篇文章主要介紹了
利用Excel导入数据库的几种实现方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
利用Excel導入數據庫的幾種實現方式
Ⅰ 直接使用navicat導入
tips:要導入的excel中的字段與數據庫表中的字段對應好
選中數據表后,點擊導入向導
選擇數據源
一路next,然后出現這一步,比對導入字段是否一致
然后再一路next,即可導入數據。
Ⅱ 利用python導入
首先把要導入的excel數據表放到和py文件相同的目錄
然后根據下面的代碼修改自己的數據庫配置和參數即可
import xlrd
import pymysql
class Add_Excel_Data_To_MySQL(object):"""Excel表格數據批量導入到MySQL庫"""def conn_pymysql(self
, host
, dbuser
, dbpassword
, dbname
):self
.conn
= pymysql
.connect
(host
=host
, user
=dbuser
, dbpassword
=dbpassword
, db
=dbname
)self
.cursor
= self
.conn
.cursor
()def excel_path(self
, file_path
, excel_table_name
):self
.excel
= xlrd
.open_workbook
(file_path
)self
.sheet_name
= self
.excel
.sheet_by_name
(excel_table_name
)def for_excel_insert_mysql(self
, db01
, db02
, db03
):self
.query
= "INSERT INTO geo ({}, {}, {}) VALUES (%s, %s, %s)".format(db01
,db02
,db03
)for r
in range(1, self
.sheet_name
.nrows
):excel_01
= self
.sheet_name
.cell
(r
, 0).value
,excel_02
= self
.sheet_name
.cell
(r
, 1).value
,excel_03
= self
.sheet_name
.cell
(r
, 2).value
,self
.values
= (excel_01
, excel_02
, excel_03
)self
.cursor
.execute
(self
.query
, self
.values
)self
.conn
.commit
()self
.cursor
.close
()self
.conn
.close
()self
.columns
= str(self
.sheet_name
.ncols
)self
.rows
= str(self
.sheet_name
.nrows
)print("一共導入了{}列, {}行數據!".format(self
.columns
, self
.rows
))if __name__
== '__main__':a
= Add_Excel_Data_To_MySQL
()a
.conn_pymysql
(host
="localhost",dbuser
="root",dbpassword
="123456",dbname
="test")a
.excel_path
("D:\Work-2021\py\geo.xlsx", "test")a
.for_excel_insert_mysql
(db01
="xxx",db02
="xxx",db03
="xxx")
Ⅲ 通過Excel直接生成insert語句
首先,選中Excel表格中的含有數據最后一列的下一列的第一格后,輸入以下代碼:
=CONCATENATE
("insert into geo(gero_name,shi,quxian,address,shi_id,quxian_id) values('",A1
,"','",B1
,"','",C1
,"','",D1
,"','",E1
,"','",F1
,"');")
確定寫好后,直接拖到最后一行,生成所有insert語句,然后將這一部分insert語句復制出來,navicat導入即可。
總結
以上是生活随笔為你收集整理的利用Excel导入数据库的几种实现方式的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。