用python将excel数据写入mysql
2016-02-24 10:16
656 查看
先在mysql创建好数据库以及数据表
以下为自己参考多个网站写的代码
# -*- coding: UTF-8 -*-
import xlrd,pymysql,sys
reload(sys)
sys.setdefaultencoding('utf-8')
def open_excel(file):
try:
data = xlrd.open_workbook(file)
return data
except Exception,e:
print str(e)
def excel_table_byname(file='/Users/apple/Desktop/test_excel.xlsx',by_name=u'Sheet1'):
data = open_excel(file)
table = data.sheet_by_name(by_name)
return table
def main():
insert_sql = 'insert into test2 (Clinic_Code, Dept_Code, Doct_Code, Diag_Name) values (%s, %s, %s, %s)'
conn = pymysql.connect(host='localhost',user='root',passwd='abysmaN169',db='test',charset='utf8')
cur = conn.cursor()
table = excel_table_byname()
nrows = table.nrows
print nrows
ncols = table.ncols
print ncols
data = []
for i in range(1,nrows):#只取第二行到最后一行
for j in range(1,ncols-2):#只取第二三四六列数据
data.append(str(table.cell(i,j).value))
print str(table.cell(i,j).value)
if j==3:
data.append(str(table.cell(i,j+2).value))
cur.execute(insert_sql,[data[0],data[1],data[2],data[3]])
data = []#重置
conn.commit() #提交
cur.close()
conn.close()
if __name__ == '__main__':
main()
xlrd使用:http://www.cnblogs.com/lhj588/archive/2012/01/06/2314181.html
以下为自己参考多个网站写的代码
# -*- coding: UTF-8 -*-
import xlrd,pymysql,sys
reload(sys)
sys.setdefaultencoding('utf-8')
def open_excel(file):
try:
data = xlrd.open_workbook(file)
return data
except Exception,e:
print str(e)
def excel_table_byname(file='/Users/apple/Desktop/test_excel.xlsx',by_name=u'Sheet1'):
data = open_excel(file)
table = data.sheet_by_name(by_name)
return table
def main():
insert_sql = 'insert into test2 (Clinic_Code, Dept_Code, Doct_Code, Diag_Name) values (%s, %s, %s, %s)'
conn = pymysql.connect(host='localhost',user='root',passwd='abysmaN169',db='test',charset='utf8')
cur = conn.cursor()
table = excel_table_byname()
nrows = table.nrows
print nrows
ncols = table.ncols
print ncols
data = []
for i in range(1,nrows):#只取第二行到最后一行
for j in range(1,ncols-2):#只取第二三四六列数据
data.append(str(table.cell(i,j).value))
print str(table.cell(i,j).value)
if j==3:
data.append(str(table.cell(i,j+2).value))
cur.execute(insert_sql,[data[0],data[1],data[2],data[3]])
data = []#重置
conn.commit() #提交
cur.close()
conn.close()
if __name__ == '__main__':
main()
xlrd使用:http://www.cnblogs.com/lhj588/archive/2012/01/06/2314181.html
相关文章推荐
- Python code
- python持久性管理pickle模块详细介绍
- Python学习之路,方法
- 使用IDAPYTHON跟踪程序执行路径-未加壳
- python脚本替换文件名中的非法字母
- Python学习(一):入门
- 关于python的input和raw_input(仅针对python2)
- python使用stub模块调用wcf
- 一个用python编写的GIS程序-simple GIS
- Python的defaultdict模块和namedtuple模块
- Python图像处理库PIL的ImageChops模块介绍
- (转载)NumPy详细教程
- Python笔记
- Python实现字典依据value排序
- python3 socket
- python request headers
- Python模块
- Python对象类型——数字对象类型/字符串对象类型/列表对象类型/字典对象类型等
- python学习笔记六之初识面向对象上(基础篇)
- Python爬虫之旅(一)