python读取excel数据插入sqlite中

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Hogan


import xlrd
import sqlite3


def read_excel(fileName):
# 打开文件excel
workBook = xlrd.open_workbook(fileName)

# 打开表格
table = workBook.sheets()[0]
# 计算文档有多少行
all_row = table.nrows

# 返回打开文档的对象,和文档的总行数
return table, all_row


def create_con(dbname):
# conn = sqlite3.connect('example2.db') # 连接数据库
conn = sqlite3.connect(dbname) # 连接数据库
# connect()方法,可以判断一个数据库文件是否存在,如果不存在就自动创建一个,如果存在的话,就打开那个数据库。
cus = conn.cursor() # 创建游标
return cus, conn


def sql_dao(da, cus):
# cus.execute('''CREATE TABLE stocks(id real ,lng REAL ,lat REAL,slp REAL ,intensity real ,utc text )''')

# 向表中插入一条数据
sql = '''insert into stocks values(%s,'%s','%s','%s','%s','%s')''' % (da[0], da[1], da[2], da[3], da[4], da[5])
cus.execute(sql)


def submit_close(conn):
# 提交当前事务,保存数据
conn.commit()
# 关闭数据库连接
conn.close()


if __name__ == '__main__':
row_all_obj, all_row_num = read_excel("datastr.xlsx")
conn, cus = create_con()
for i in range(1, all_row_num + 1):
data = row_all_obj.row_values(i)
sql_dao(data,cus )
print("插入第", i, "条")
submit_close(conn)
posted @ 2020-05-12 10:32  老鲜肉  阅读(1811)  评论(0编辑  收藏  举报