Python读写Excel文件

本文介绍了一种将Excel数据迁移到MySQL数据库的方法,利用Python的xlrd和xlsxwriter模块读取并转换数据,并解决了在Excel 2007及以上版本中使用不同模块遇到的问题。
import xlrd,xlsxwriter,mysql.connector,time

oldwb = xlrd.open_workbook(r'D:\工作资料\统计数据\old.xlsx')
oldws = oldwb.sheets()[0]

newwb = xlsxwriter.Workbook(r'D:\工作资料\统计数据\result.xlsx')
newws = newwb.add_worksheet('userId')


def getConn():
    # 连接数据库
    conn = mysql.connector.connect(user='root', password='mysql', host='localhost',database='waterway')
    return conn
conn = getConn()
cursor = conn.cursor()

for rownum in range(1,oldws.nrows):
	mac = oldws.row(rownum)[1].value
	sql = 'select userId from equipmentinfo where equipmentMac = "' + mac +'"'
	print('sql is %s' %sql)
	cursor.execute(sql)
	userIds = ''
	for r in cursor.fetchall():
		userIds = userIds.join([r[0],','])
	if userIds.endswith(','):
		userIds = userIds[:-1]
	print('userIds is %s' %userIds)
	newws.write(rownum, 0, userIds)

newwb.close()
cursor.close()
conn.close()

使用xlrd模块,读取excel中的值,但是在使用oldws.put_cell()方法时,发现excel 2007以上版本,数据保存不上,使用xlwt模块,结果保存的文件打不开。经过一番折腾,选择了xlsxwrite.

使用了xlsxwrite模块,创建新的worksheet,把数据通过newws.write()写入到excel中。

转载于:https://my.oschina.net/friendship/blog/734696

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值