Python讀入Excel資料存入MySQL

2021-10-17 19:32:22 字數 1792 閱讀 4621

import xlrd

import pymysql

from datetime import datetime

from xlrd import xldate_as_tuple

# 開啟資料所在的工作簿,以及選擇存有資料的工作表

book = xlrd.open_workbook(

"測試表.xls"

)sheet = book.sheet_by_name(

"sheet1"

)# 建立乙個mysql連線

conn = pymysql.connect(

host=

'127.0.0.1'

, user=

'root'

, password=

'111111'

, db=

'test'

, port=

3306

, charset=

'utf8'

)# 獲得游標

cur = conn.cursor(

)# 建立插入sql語句

query =

'insert into incrementelectrictable(incremenvalue, incrementype, address, collectiondate, areaname) values (%s,%s,%s,%s,%s)'

# 建立乙個for迴圈迭代讀取xls檔案每行資料的, 從第二行開始是要跳過標題行,

i = sheet.nrows

for r in

range(1

, sheet.nrows)

: incremenvalue = sheet.cell(r,0)

.value

incrementype = sheet.cell(r,1)

.value

address = sheet.cell(r,2)

.value

collectiondate = datetime(

*xldate_as_tuple(sheet.cell(r,3)

.value,0)

).strftime(

'%y-%m-%d %h:%m:%s'

) areaname = sheet.cell(r,4)

.value

# comment = sheet.cell(r, 5).value

# equipmentname = sheet.cell(r, 3).value

# area = sheet.cell(r, 4).value

# addtime = cell_date

# status = sheet.cell(r, 6).value

values =

(incremenvalue, incrementype, address, collectiondate, areaname)

# 執行sql語句

cur.execute(query, values)

cur.close(

)conn.commit(

)conn.close(

)columns =

str(sheet.ncols)

rows =

str(sheet.nrows)

print

("匯入 "

+ columns +

" 列 "

+ rows +

" 行資料到mysql資料庫!"

)

python讀入資料

二.從檔案讀取資料 語法格式 var name input 提示資訊 讀取鍵盤輸入,儲存為string型別,並賦值給變數var name 當需要輸入多個資料時 list var list var input 請輸入多個資料,以空格區分 split int list var 0 語法格式 import...

Excel讀入dataset資料丟失的問題

1 引言 在應用程式的設計中,經常需要讀取excel資料或將excel資料匯入轉換到其他資料載體中,例如將excel資料通過應用程式匯入sql sever等資料庫中以備使用。筆者在開發 汽車產業鏈asp協同商務平台 中遇到了類似需求。某汽車整車生產企業需要將其車輛發車資訊發布到汽車產業鏈平台上去,其...

python讀資料 python中如何讀入資料

python的文字處理是經常碰到的乙個問題,python的文字檔案的內容讀取中,有三類方法 read readline readlines 這三種方法各有利弊,下面逐一介紹其使用方法和利弊。read read 是最簡單的一種方法,一次性讀取檔案的所有內容放在乙個大字串中,即存在記憶體中file ob...