因为工作需要,所以测试一下使用Python读Excel数据到MySQL,在此记录下.
#!/usr/bin/env python#coding:utf-8import xlrdimport MySQLdbimport datetimexlsfile=r'C:\Users\XUWU\Desktop\data.xlsx'book = xlrd.open_workbook(xlsfile)#获取sheet的数量count = len(book.sheets()) #设置连接数据库database = MySQLdb.connect(host='192.168.1.30',user='root',passwd='123456',db='crm')#设置字符集database.set_character_set('utf8')cursor = database.cursor()cursor.execute('SET NAMES utf8;') cursor.execute('SET CHARACTER SET utf8;')cursor.execute('SET character_set_connection=utf8;')starttime = datetime.datetime.now()print '开始时间:%s' % (starttime)#循环sheetfor i in range(0,count-1): sheet = book.sheet_by_index(i) query = """INSERT INTO bill_test ( member_id, name, tel, phone, dq_datetime, address, parking) VALUES ( %s, %s, %s, %s, %s, %s, %s)""" #循环每一行 for r in range(1, sheet.nrows): #idseq = sheet.cell(r,0).value member_id = sheet.cell(r,1).value name = sheet.cell(r,2).value tel = sheet.cell(r,3).value phone = sheet.cell(r,4).value #dq_datetime = sheet.cell(r,5).value #读日期这里要处理一下,不然全变成数字了 dq_datetime_num=xlrd.xldate_as_tuple(sheet.cell(r,5).value,0) dq_datetime = '%s/%s/%s' % (dq_datetime_num[0],dq_datetime_num[1],dq_datetime_num[2]) address = sheet.cell(r,6).value parking = sheet.cell(r,7).value values = (member_id, name, tel, phone, dq_datetime, address, parking) #print query,values cursor.execute(query, values) cursor.close()database.commit()database.close()endtime=datetime.datetime.now()print '结束时间:%s' % (endtime)print '用时:%s 秒' % (endtime-starttime)
测试表结构:
CREATE TABLE `bill_test` ( `idseq` mediumint(10) unsigned NOT NULL AUTO_INCREMENT, `member_id` int(10) DEFAULT NULL, `name` varchar(20) DEFAULT NULL, `tel` varchar(20) DEFAULT NULL, `phone` varchar(20) DEFAULT NULL, `dq_datetime` varchar(20) DEFAULT NULL, `address` varchar(200) DEFAULT NULL, `parking` varchar(200) DEFAULT NULL, PRIMARY KEY (`idseq`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 |
程序执行情况:
查询结果: