使用Python將Excel中的數據導入到MySQL
工具
- Python 2.7
- xlrd
- MySQLdb
安裝
- Python
對於不同的系統安裝方式不同,Windows平台有exe安裝包,Ubuntu自帶。使用前請使用下面的命令確保是2.7.x版本:
python --version
- xlrd :
這是一個擴Python包,可以使用pip包管理工具安裝:pip install xlrd
- MySQLdb
為MySQL 的Python驅動接口包,可以到http://sourceforge.net/projects/mysql-python/下載安裝。在Ubuntu你可以使用sudo apt-get install python-mysql
安裝
實現數據轉移
功能很簡單,直接在代碼中注釋了
""" 功能:將Excel數據導入到MySQL數據庫 """ import xlrd import MySQLdb # Open the workbook and define the worksheet book = xlrd.open_workbook("pytest.xls") sheet = book.sheet_by_name("source") #建立一個MySQL連接 database = MySQLdb.connect (host="localhost", user = "root", passwd = "", db = "mysqlPython") # 獲得游標對象, 用於逐行遍歷數據庫數據 cursor = database.cursor() # 創建插入SQL語句 query = """INSERT INTO orders (product, customer_type, rep, date, actual, expected, open_opportunities, closed_opportunities, city, state, zip, population, region) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""" # 創建一個for循環迭代讀取xls文件每行數據的, 從第二行開始是要跳過標題 for r in range(1, sheet.nrows): product = sheet.cell(r,).value customer = sheet.cell(r,1).value rep = sheet.cell(r,2).value date = sheet.cell(r,3).value actual = sheet.cell(r,4).value expected = sheet.cell(r,5).value open = sheet.cell(r,6).value closed = sheet.cell(r,7).value city = sheet.cell(r,8).value state = sheet.cell(r,9).value zip = sheet.cell(r,10).value pop = sheet.cell(r,11).value region = sheet.cell(r,12).value values = (product, customer, rep, date, actual, expected, open, closed, city, state, zip, pop, region) # 執行sql語句 cursor.execute(query, values) # 關閉游標 cursor.close() # 提交 database.commit() # 關閉數據庫連接 database.close() # 打印結果 print "" print "Done! " print "" columns = str(sheet.ncols) rows = str(sheet.nrows) print "我剛導入了 " %2B columns %2B " 列 and " %2B rows %2B " 行數據到MySQL!"