使用python将excel数据导入到mysql

最后编辑时间: 2017-10-23

如何将mysql导入到excel,今天我们就讲讲简单的将excel数据导入到mysql

python是使用模块xlrd来导入到mysql的,使用pymysql(python2.X的使用MySQLdb)来链接mysql数据库的

-------------代码-------------------------

-- coding: utf-8 --

import xlrd
import pymysql

设置基本变量

_host = 'localhost'
_db = '13net'
_user = 'root'
_password = 'root'
_table = 'net_members_bak'
_excel_name = './tes2t.xlsx'

open excel

excel = xlrd.open_workbook(_excel_name)
sheet = excel.sheet_by_index(0)

rows = sheet.nrows
cols = sheet.ncols
data = []
fields=''

创建好要数据,如果第一行是表头的话,从1开始,若第一行就是数据,从0开始

在这里有必要提醒大家的是,这只是个简单的数据处理,如果你的数据有一些特殊的字符,或者数据,需要先将数据处理好了之后再来打包导入

for i in range(1,rows):
data.append(sheet.row_values(i))

for i in range(0,cols):

fields = fields+'%s,'

print(fields)

mysql

conn = pymysql.connect(host=_host,user=_user,password=_password,db=_db,charset='utf8')
cursor = conn.cursor()

个人觉得最好先创建好表之后来导入数据把,如果要新建的话,也可以在这执行语句新建,但是不建议这么做

批量插入数据

cursor.executemany("insert into "+_table+" values("+fields[:-1]+");" ,data)

不要忘记commit

conn.commit()

-------------end-------------------------

在这里有必要提醒大家的是,这只是个简单的数据处理,如果你的数据有一些特殊的字符,或者数据,需要先将数据处理好了之后再来打包导入

总的来说python在mysql=====excel数据的导入导出的的确确是要比php简单易懂很多,还是要多学学其他语言,才能看到更好的方法

github地址:https://github.com/ruke318/python-mysql-excel

请在下方留下您的评论.加入TG吹水群