最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Python如何实现excel转sqlite
时间:2017-07-19 编辑:简简单单 来源:一聚教程网
本文实例讲述了Python实现excel转sqlite的方法。分享给大家供大家参考,具体如下:
Python环境的安装配置就不说了,个人喜欢pydev的开发环境。
python解析excel需要使用第三方的库,这里选择使用xlrd
先看excel内容:
然后是生成的数据库:
下面是源代码:
代码如下 | 复制代码 |
#!/usr/bin/python # encoding=utf-8 ''''' Created on 2013-4-2 @author: ting ''' fromxlrdimportopen_workbook importsqlite3 importtypes defread_excel(sheet): # 判断有效sheet ifsheet.nrows >0andsheet.ncols >0: forrowinrange(1, sheet.nrows): row_data=[] forcolinrange(sheet.ncols): data=sheet.cell(row, col).value # excel表格内容数据类型转换 float->int,unicode->utf-8 iftype(data)istypes.UnicodeType: data=data.encode("utf-8") eliftype(data)istypes.FloatType: data=int(data) row_data.append(data) check_data_length(row_data) # 检查row_data长度 defcheck_data_length(row_data): iflen(row_data)==3: insert_sqlite(row_data) definsert_sqlite(row_data): # 打开数据库(不存在时会创建数据库) con=sqlite3.connect("test.db") cur=con.cursor() try: cur.execute("create table if not exists contacts(_id integer primary key "\ "autoincrement,name text,age integer,number integer)") # 插入数据不要使用拼接字符串的方式,容易收到sql注入攻击 cur.execute("insert into contacts(name,age,number) values(?,?,?)", row_data) con.commit() exceptsqlite3.Error as e: print"An error occurred: %s", e.args[0] finally: cur.close con.close xls_file="test.xls" book=open_workbook(xls_file) forsheetinbook.sheets(): read_excel(sheet) print"------ Done ------" |
希望本文所述对大家Python程序设计有所帮助。
-
上一个: PHPstorm快捷键介绍
相关文章
- PHP导出数据超时的优化建议解读 10-31
- PHP之mysql位运算解析 10-31
- Laravel实现登录跳转功能解析 10-31
- php双向队列解读 10-31
- Laravel异常上下文解决教程 10-24
- php数组查询元素位置方法介绍 10-24