使用python将excel数据导入数据库
使用python将excel数据导入数据库
- 因为需要对数据处理,将excel数据导入到数据库,记录一下过程。
- 使用到的库:xlrd 和 pymysql (如果需要写到excel可以使用xlwt)
- 直接丢代码,使用python3,注释比较清楚。
- 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
importxlrdimportpymysql# import importlib# importlib.reload(sys) #出现呢reload错误使用defopen_excel():try:book=xlrd.open_workbook("XX.xlsx")#文件名,把文件与py文件放在同一目录下except:print("open excel file failed!")try:sheet=book.sheet_by_name("sheet名称")#execl里面的worksheet1returnsheetexcept:print("locate worksheet in excel failed!")#连接数据库try:db=pymysql.connect(host="127.0.0.1",user="root",passwd="XXX",db="XXX",charset='utf8')except:print("could not connect to mysql server")defsearch_count():cursor=db.cursor()select="select count(id) from XXXX"#获取表中xxxxx记录数cursor.execute(select)#执行sql语句line_count=cursor.fetchone()print(line_count[0])definsert_deta():sheet=open_excel()cursor=db.cursor()foriinrange(1, sheet.nrows):#第一行是标题名,对应表中的字段名所以应该从第二行开始,计算机以0开始计数,所以值是1name=sheet.cell(i,0).value#取第i行第0列data=sheet.cell(i,1).value#取第i行第1列,下面依次类推print(name)print(data)value=(name,data)print(value)sql="INSERT INTO XXX(name,data)VALUES(%s,%s)"cursor.execute(sql,value)#执行sql语句db.commit()cursor.close()#关闭连接insert_deta()db.close()#关闭数据print("ok ")XXX里自行修改自己的名称。
- 说明:对于不规则的单元格,例如合并过的单元格会取到空值。
- 有机会把数据库写到excel贴上来。
- 优化了一下这个程序
- 123456789101112131415161718192021222324252627282930313233343536373839404142
importpymysqlimportxlrd# 连接数据库try:db=pymysql.connect(host="127.0.0.1", user="root",passwd="XXX",db="XXX",charset='utf8')except:print("could not connect to mysql server")defopen_excel():try:book=xlrd.open_workbook("XXX.xlsx")#文件名,把文件与py文件放在同一目录下except:print("open excel file failed!")try:sheet=book.sheet_by_name("XXX")#execl里面的worksheet1returnsheetexcept:print("locate worksheet in excel failed!")definsert_deta():sheet=open_excel()cursor=db.cursor()row_num=sheet.nrowsforiinrange(1, row_num):# 第一行是标题名,对应表中的字段名所以应该从第二行开始,计算机以0开始计数,所以值是1row_data=sheet.row_values(i)value=(row_data[0],row_data[1],row_data[2],row_data[3])print(i)sql="INSERT INTO demo_yangben(xxx,xxxx,xxxx,xxxx)VALUES(%s,%s,%s,%s)"cursor.execute(sql, value)# 执行sql语句db.commit()cursor.close()# 关闭连接open_excel()insert_deta() - 再改一下,每一万条数据写入到数据库一次
- 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
importpymysqlimportxlrdimportsys'''连接数据库args:db_name(数据库名称)returns:db'''defmysql_link(de_name):try:db=pymysql.connect(host="127.0.0.1", user="xxx",passwd="xxx",db=xxx,charset='utf8')returndbexcept:print("could not connect to mysql server")'''读取excel函数args:excel_file(excel文件,目录在py文件同目录)returns:book'''defopen_excel(excel_file):try:book=xlrd.open_workbook(excel_file)# 文件名,把文件与py文件放在同一目录下print(sys.getsizeof(book))returnbookexcept:print("open excel file failed!")'''执行插入操作args:db_name(数据库名称)table_name(表名称)excel_file(excel文件名,把文件与py文件放在同一目录下)'''defstore_to(db_name, table_name, excel_file):db=mysql_link(db_name)# 打开数据库连接cursor=db.cursor()# 使用 cursor() 方法创建一个游标对象 cursorbook=open_excel(excel_file)# 打开excel文件sheets=book.sheet_names()# 获取所有sheet表名forsheetinsheets:sh=book.sheet_by_name(sheet)# 打开每一张表row_num=sh.nrowsprint(row_num)list=[]# 定义列表用来存放数据num=0# 用来控制每次插入的数量foriinrange(1, row_num):# 第一行是标题名,对应表中的字段名所以应该从第二行开始,计算机以0开始计数,所以值是1row_data=sh.row_values(i)# 按行获取excel的值value=(row_data[0], row_data[1], row_data[2], row_data[3], row_data[4], row_data[5], \row_data[6], row_data[7], row_data[8], row_data[9], row_data[10], row_data[11], row_data[12],row_data[13], row_data[14])list.append(value)# 将数据暂存在列表num+=1if( num>=10000):# 每一万条数据执行一次插入print(sys.getsizeof(list))sql="INSERT INTO "+table_name+" (time, xingbie, afdd, xzb, yzb, cfbj, jjlbmc, \bjlbmc, bjlxmc, bjlxxlmc, gxqymc,gxdwmc, afql, afxqxx, cjdwmc)\VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"cursor.executemany(sql,list)# 执行sql语句num=0# 计数归零list.clear()# 清空listprint("worksheets: "+sheet+" has been inserted 10000 datas!")print("worksheets: "+sheet+" has been inserted "+str(row_num)+" datas!")db.commit()# 提交cursor.close()# 关闭连接db.close()if__name__=='__main__':store_to('demo','demo_yangben','xxx.xlsx') - 思考,如果数据插入有错误,怎么解决,
- 其实有很多数据库工具可以直接来解决这个问题,注意字符转换的格式就好。
- 批量插入数据请看: https://www.cnblogs.com/longbigbeard/p/9317141.html
使用python将excel数据导入数据库的更多相关文章
- [Asp.net]常见数据导入Excel,Excel数据导入数据库解决方案,总有一款适合你!
引言 项目中常用到将数据导入Excel,将Excel中的数据导入数据库的功能,曾经也查找过相关的内容,将曾经用过的方案总结一下. 方案一 NPOI NPOI 是 POI 项目的 .NET 版本.POI ...
- 如何把excel数据导入数据库
这里介绍2种把excel数据导入oracle数据库的方法. 1. 在excel中生成sql语句. 1)在数据列的右侧,第一行的任何位置输入="insert into table(xx,yyy ...
- C#将Excel数据导入数据库(MySQL或Sql Server)
最近一直很忙,很久没写博客了.今天给大家讲解一下如何用C#将Excel数据导入Excel,同时在文章最后附上如何用sqlserver和mysql工具导入数据. 导入过程大致分为两步: 1.将excel ...
- Excel数据导入数据库
maven依赖 <!--excel相关依赖--> <dependency> <groupId>org.apache.poi</groupId> < ...
- 转:[Asp.net]常见数据导入Excel,Excel数据导入数据库解决方案,总有一款适合你!
引言 项目中常用到将数据导入Excel,将Excel中的数据导入数据库的功能,曾经也查找过相关的内容,将曾经用过的方案总结一下. 方案一 NPOI NPOI 是 POI 项目的 .NET 版本.POI ...
- PHPExcel将Excel数据导入数据库
<?php //PHPExcel读取导入Excel数据到数据库(2003,2007通用)使用方法: //先用excel2array()方法将excel表中的数据存储到数组,在从遍历二维数组将数据 ...
- 利用python将excel数据导入mySQL
主要用到的库有xlrd和pymysql, 注意pymysql不支持python3 篇幅有限,只针对主要操作进行说明 连接数据库 首先pymysql需要连接数据库,我这里连接的是本地数据库(数据库叫ld ...
- 将Excel数据导入数据库
Excel如下,这页工作表名叫“线路” 数据库表如下 using System; using System.Collections.Generic; using System.Linq; using ...
- ASP.NET Excel数据导入数据库
<identity impersonate="true"/> 是指模拟IIS身份验证 導入錯誤時可刪除 protected void btnImport_Click(o ...
随机推荐
- 设计模式(二)策略模式(Strategy)
1.分析项目中变化部分与不变部分 2.多用组合,少用继承:用行为类组合,而不是行为的继承 案例: 第一步,把行为抽象为接口 package top.littlepage.designPattern.S ...
- 学习笔记56—Endnote参考文献格式调整
论文写作
- CentOS7 上安装 Lua5.3
1.CentOS7默认已经安装了5.1.4 ①查看当前lua版本号:lua -v Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio ②查看lua和 ...
- ionic日历插件
1:引入插件的两个文件 timePicker.js 和timePicker.css文件 2:填加插件模块到项目模块中CorderYuan->app.js的moudule 3:在 ...
- Selenium WebDriver Api 知识梳理
之前一直没有系统的梳理WebDriver Api的相关知识,今天借此机会整理一下. 1.页面元素定位 1.1.8种常用定位方法 # id定位 driver.find_element_by_id() # ...
- ubuntu下安装anaconda
1. 到官网http://continuum.io/downloads下载anaconda. 选择linux64-bit-python2.7 2. 安装anaconda,在终端输入:cd ~/Do ...
- 百度Apollo搭建步骤(待更新)
百度Apollo搭建步骤 ##一.安装ubuntu16.04 无需多说,安装完成打开命令行. ##二.下载Apollo镜像 git clone https://github.com/ApolloAut ...
- HTML 第十一章总结
# 第十一章总结:本章的标题为:layout and positioning Arranging Element##前言:这一章节,通过已经知道的 box model 的概念,进行讲述关于 layou ...
- English trip V1 - B 16. Giving Reasons 提供个人信息 Teacher:Lamb Key: Why/Because
In this lesson you will learn how to give reasons for something you've done. 课上内容(Lesson) Why do peo ...
- 用C#实现多种方式播放Wav声音
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...