python 读取xlsx特定页_python 读取 Excel

这段代码是把Excel数据导入到MySQL中,后续会比较Excel数据正确性,并将错误数据导出到Excel。

import xlrd, MySQLdb

def db_connect():

conn = MySQLdb.connect("localhost", "root", "root", "test")

return conn

def open_excel(filename):

excel = xlrd.open_workbook(filename)

return excel

def read_excel():

sheet = open_excel('users.xlsx').sheet_by_index(0)

nrows = sheet.nrows

conn = db_connect()

conn.set_character_set("utf8")

cursor = conn.cursor()

try:

for i in range(0, nrows):

name = sheet.cell_value(i, 0)

num = sheet.cell_value(i, 1)

cursor.execute("insert into users(name, num) values (%s, %s)", (name, num))

except Exception, e:

print e

conn.rollback()

conn.commit()

conn.close()

def main():

read_excel()

if __name__ == '__main__':

main()

下面是比较用户数据:

import MySQLdb

def conn_location():

conn = MySQLdb.connect("localhost", "root", "root", "test")

return conn

def conn_remote():

conn = MySQLdb.connect("localhost", "intime4", "root", "intime4")

return conn

def locationData():

conn = conn_location()

conn.set_character_set("utf8")

cursor = conn.cursor()

cursor.execute("select * from users")

results = cursor.fetchall()

conn.close()

return results

def remoteData(id):

conn = conn_remote()

conn.set_character_set("utf8")

cursor = conn.cursor()

sql = "select id, cust_name, credentials_number from od_order_info where credentials_number = '%s'" % id

cursor.execute(sql)

results = cursor.fetchall()

conn.close()

return results

def checkRemoteData():

lResults = locationData()

for l in lResults:

name = l[1]

id = l[2].strip()

rResults = remoteData(id)

if len(rResults) == 0:

print id, name

for r in rResults:

if name != r[1]:

print r[0], r[1], r[2]

def main():

checkRemoteData()

if __name__ == '__main__':

main()

由于不一致的数据量很少,就没有导出到Excel。

但过程中遇到个问题,从数据库中读取数据时在第一个for循环中有一条数据不知道为什么前面出现了空格,最后使用l[2].strip()解决了,如果有知道答案的请回复我,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值