python 解析excel資料並插入資料庫(可執行)
阿新 • • 發佈:2019-01-09
背景:應業務要求需要不定期將一些excel資料匯入到線上資料庫
run.py實現如下:
#encoding=utf-8
import xlrdfrom configparser import ConfigParser
import pymysql
import sys
try:
book = xlrd.open_workbook("xxxxxx.xlsx") #檔名,把檔案與py檔案放在同一目錄下
except:
print("open excel file failed!")
try:
sheet = book.sheet_by_name("工作表1") #execl裡面的worksheet1
except:
print("locate worksheet in excel failed!")
#連線資料庫
try:
database = pymysql.connect(host="XXXXXXXXXX.mysql.rds.aliyuncs.com",user="xxxxxx_rw",
passwd="xxxxxxxxxx",
db="xxxxxxxxx",
charset='utf8')
except:
print("could not connect to mysql server(XXXXXXXXXX.mysql.rds.aliyuncs.com)")
cursor = database.cursor()
select = "select count(id) from xxxxx" #獲取表中xxxxx記錄數
cursor.execute(select) #執行sql語句
line_count = cursor.fetchone()
#print(line_count[0])
for i in range(1, sheet.nrows): #第一行是標題名,對應表中的欄位名所以應該從第二行開始,計算機以0開始計數,所以值是1
intention_type = sheet.cell(i,0).value #取第i行第0列iphone = sheet.cell(i,1).value#取第i行第1列,下面依次類推
addrs = sheet.cell(i,2).value
intention_date = sheet.cell(i,3).value
uname = sheet.cell(i,4).value
ID_card = sheet.cell(i,5).value
intention_car = sheet.cell(i,6).value
comment = sheet.cell(i,7).value
#create_time = now()
value = (uname,ID_card,iphone,addrs,intention_car,intention_type,intention_date,comment)
insert = "INSERT INTO dm_intention_pool(name,id_card_no,mobile,addr,model_code,type,intention_time,ext)VALUES(%s,%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(insert,value) #執行sql語句
update = "UPDATE `xxxxx` SET `create_time` =now(),`update_time` =now() where id > %s"
cursor.execute(update,line_count[0]) #執行sql語句
database.commit()#提交
cursor.close() #關閉連線
database.close()#關閉資料
print ("")
print ("Done! ")
print ("")
執行:
python3 run.py