栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

利用 Python 将 Excel 中的数据写入 SQLite

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

利用 Python 将 Excel 中的数据写入 SQLite

利用Python将Excel中的数据写入SQLite
from xlrd import open_workbook
import sqlite3

# 测试数据系为某人的高考志愿填报表

# 从Excel表格中读入数据, 并写入dataList中进行存储
book = open_workbook(r"D:系统默认桌面Student.xls", encoding_override="utf-8")
sheet_name = book.sheet_names()[0]
sheet = book.sheet_by_name(sheet_name)
dataList = []
for i in range(1, sheet.nrows):
    data = []
    for j in range(0, sheet.ncols):
        data.append(str(sheet.cell(i, j).value))  # 以字符串的形式写入
    dataList.append(data)
# for i in range(0, len(dataList)):  # 打印datalist中的内容
#     print(dataList[i])

# 新建表格
con = sqlite3.connect(r"D:CodeLibraryspiderdatabaseStudent.db")
cursor = con.cursor()  # 获取游标
sql = '''
    create table if not exists Student
     (
        id integer primary key autoincrement,
        序号 integer not null,
        专业 text not null,
        院校 text not null,
        计划数 integer not null,
        位次 integer not null,
        录取分 real not null,
        选科要求 text not null,
        代号 text not null
     );
'''
cursor.execute(sql)
con.commit()

'''
大部分是借鉴网课资料, 网课链接: https://www.bilibili.com/video/BV12E411A7ZQ?spm_id_from=..search-card.all.click&vd_source=d0f880a66be8775389e528d9ca528d05
'''
for data in dataList:
    for index in range(len(data)):
        if index == 0 or index == 3 or index == 4 or index == 5:
            continue
        data[index] = '"' + data[index] + '"'
    sql2 = '''
        insert into Student(
        序号, 专业, 院校, 计划数, 位次, 录取分, 选科要求, 代号)
        values(%s)''' % ",".join(data)
    cursor.execute(sql2)
    con.commit()
cursor.close()
con.close()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1009113.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号