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

python 2.7導入excel到mysql

分享 image shee rmi 目錄 set row mysq sheet

文件目錄如下

技術分享圖片

# -*- 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!"

python 2.7導入excel到mysql