python 读取excel数据到mysql

本文提供了一个使用Python将Excel文件中的数据批量导入到MySQL数据库的具体示例。该过程涉及到了Python操作Excel文件、连接MySQL数据库及执行批量插入操作等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb
import os
import sys
import re
reload(sys)
sys.setdefaultencoding( "utf-8" )
import time
import datetime
today=datetime.date.today()
oneday=datetime.timedelta(days=1)
to_yes=today-oneday
yesterday=to_yes.strftime('%Y%m%d')
currentDate=time.strftime('%Y%m%d',time.localtime())
import MySQLdb
import xlrd
from openpyxl import Workbook
from openpyxl.compat import range
xlsfile=r'C:\Users\cherry\Desktop\defriend_0\aaaaa.xlsx'
book=xlrd.open_workbook(xlsfile)
count=len(book.sheets())
print count
conn = MySQLdb.connect(host='192.168.10.70', user='dlan', passwd='root123', db='yy_access', charset="utf8")
conn.set_character_set('utf8')
cursor = conn.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)
#读取sheet数量
for i in range(0,count):
   print i
   sheet=book.sheet_by_index(i)
   print sheet
   query="""insert into yy_access.ca_user_phone_score(phone_number,score,notic)values(%s,%s,%s)"""
   ##循环每一行,不包含标题
   for r in range(1,sheet.nrows):
       phone_number = sheet.cell(r, 0).value
       score = sheet.cell(r, 1).value
       notic= sheet.cell(r, 2).value
       values=(phone_number,score,notic)
       print values,query
       cursor.execute(query,values)

cursor.close()
conn.commit()
conn.close()
endtime=datetime.datetime.now()
print '结束时间:%s' % (endtime)

print '用时:%s 秒' % (endtime-starttime)


本文转自 DBAspace 51CTO博客,原文链接:
http://blog.51cto.com/dbaspace/1914846


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值