sqlitepython导入数据_Python导入excel数据到sqlite;

该博客展示了如何利用Python的xlrd和sqlite3库将Excel文件中的数据批量导入到SQLite数据库中。首先,通过xlrd打开Excel工作簿,然后获取数据开始的行索引。接着,检查并创建数据库,如果不存在则创建Tasks表。最后,遍历Excel数据,为每一行生成唯一ID,并将数据插入到Tasks表中。
摘要由CSDN通过智能技术生成

#coding=utf-8

importxlrdimportsqlite3importosimportuuiddefinsert_data_to_db(path):

wb=xlrd.open_workbook(path)print(wb.sheet_names())

sheet=wb.sheets()[0]

nrows=sheet.nrows#获取任务行里索引

begin_index =0

end_index=begin_indexfor i inrange(nrows):

col_value= sheet.row(i)[1].valueif(begin_index == 0 and col_value == "责任人"):

begin_index= i + 1end_index=begin_indexif(begin_index != 0 and col_value == ""):

end_index=ibreak

print(begin_index)print(end_index)#检查创建数据库

db_path = "zb.db"is_db_exist=os.path.exists(db_path)

conn=sqlite3.connect(db_path)

cursor=conn.cursor()if notis_db_exist:

conn.execute('''CREATE TABLE IF NOT EXISTS Tasks(

Id varchar PRIMARY KEY,

Name varchar,

Task varchar,

PercentageTask varchar,

BeginTime datetime,

EndTime datetime,

Memo varchar,

FileName varchar)''')

conn.commit()#获取文件名

(_file_path, file_name) =os.path.split(path)

sql= '''INSERT OR REPLACE INTO Tasks

(Id,Name,Task,PercentageTask,BeginTime,EndTime,Memo,FileName) VALUES (?,?,?,?,?,?,?,?)'''

#遍历内容插入数据库

for i inrange(begin_index, end_index):

col_id=str(uuid.uuid1())

col_name= sheet.row(i)[1].value

col_task= sheet.row(i)[2].value

col_percentage_task= sheet.row(i)[3].value

col_begin_time= sheet.row(i)[4].value

col_end_time= sheet.row(i)[5].value

col_memo= sheet.row(i)[6].value

cursor.execute(sql, (col_id, col_name, col_task, col_percentage_task,

col_begin_time, col_end_time, col_memo, file_name))

conn.commit()defmain():

file_dir= "zb"

for _root, _dirs, files inos.walk(file_dir):for file infiles:

insert_data_to_db(file_dir+"/"+file)

main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值