当前位置: 首页 > news >正文

将excel导入到sqlite的方法代码

Python实现excel转sqlite的方法,具体如下:
Python环境的安装配置就不说了,个人喜欢pydev的开发环境。
python解析excel需要使用第三方的库,这里选择使用xlrd


 

下面是源代码:

#!/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 ------"
 

 

http://www.lryc.cn/news/58130.html

相关文章:

  • Redis主从复制、哨兵和集群部署
  • protobuf序列化
  • 更新时无冲突的情况(阁瑞钛伦特软件-九耶实训)
  • 3.4 函数的单调性和曲线的凹凸性
  • LeetCode 404. 左叶子之和 | C++语言版
  • arm架构安装Rancher并导入k8s集群解决Error: no objects passed to apply
  • 安装PaddleSpeech
  • UE “体积”的简单介绍
  • 微信 JAVA SDK 封装
  • 上海智慧校园视频智能分析算法 yolov7
  • 【树】你真的会二叉树了嘛? --二叉树LeetCode专题
  • 《LeetCode 热题 HOT 100》——寻找两个正序数组的中位数
  • Unity- 游戏结束以及重启游戏
  • NGK BeCu8·11铜合金板材
  • 电脑突然死机怎么办?正确做法在这!
  • 基于cell数组的MATLAB仿真(附上完整仿真源码)
  • 电脑蓝屏问题排查
  • SpringBoot配置slf4j + logback
  • JAVA——网络编程基本概念
  • [JavaEE]----Spring02
  • 笔记本可自行更换CPU、独显了,老外用它手搓了台“PS5”
  • Linux uart驱动框架
  • 第一个禁止ChatGPT的西方国家
  • Web 攻防之业务安全:Session会话注销测试.
  • 4月最新编程排行出炉,第一名ChatGPT都在用~
  • 生成不保存在服务器的附件,并以附件形式发送邮件
  • Golang Gin框架HTTP上传文件
  • BM36-判断是不是平衡二叉树
  • Quartz 单例定时任务
  • 不要告诉同事你要离职!打算跳槽,新公司开出两倍薪资,私下告诉要好的同事,却被同事出卖给领导!...