1. 程式人生 > >python 2.7匯入excel到mysql

python 2.7匯入excel到mysql

檔案目錄如下

# -*- coding:utf-8 -*-
import xlrd
import MySQLdb
# Open the workbook and define the worksheet
book = xlrd.open_workbook("3.xls")
sheet = book.sheet_by_name("Table1")

#建立一個MySQL連線
database = MySQLdb.connect (host="", user = "", passwd = "", db = "", port = 3306, charset='utf8')

# 獲得遊標物件, 用於逐行遍歷資料庫資料
cursor = database.cursor()

# 建立插入SQL語句
query = """INSERT INTO t_test (id_card) VALUES (%s)"""
# 建立一個for迴圈迭代讀取xls檔案每行資料的, 從第二行開始是要跳過標題
for r in range(1, sheet.nrows):
id_card = sheet.cell(r,0).value

values = (id_access,id_user,haspermission,id_operation)

# 執行sql語句
cursor.execute(query, values)

# 關閉遊標
cursor.close()

# 提交
database.commit()

# 關閉資料庫連線
database.close()

# 列印結果
print ""
print "Done! "
print ""
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print u"我剛匯入了 " +columns + u" 列 and " + rows + u" 行資料到MySQL!"