参考:https://www.cnblogs.com/ybjourney/p/5523878.html
因为文件部分看得晕乎乎的,所以略去了文件转码的部分,修改了一下,结合学生表,只留下简单的部分
将students.xls和py文件放在同一个目录下,students.xls中的内容如下:
代码如下:
import sqlite3
import xlrd
# 建立数据库
def createDataBase():
cn = sqlite3.connect('students.db')
cn.execute('''CREATE TABLE IF NOT EXISTS TB_STUDENTS
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
CODE INTEGER,
NAME TEXT,
Chinese TEXT,
Mathematic TEXT,
English TEXT);''')
cn.commit()
cn.close()
# 解析excel文件并将其存储到sqlite
def readExcel(filename, cn):
# 读取
workbook = xlrd.open_workbook(filename)
# 获取sheet
sheet_name = workbook.sheet_names()[0]
sheet = workbook.sheet_by_name(sheet_name)
for i in range(1, sheet.nrows):
temp = []
for j in range(0, sheet.ncols):
temp.append(sheet.cell(i, j).value)
cn.execute("insert into TB_STUDENTS (CODE, NAME, Chinese, Mathematic, English) "
"values('%s','%s','%s','%s','%s')"
% (temp[0], temp[1], temp[2], temp[3], temp[4]))
#itemCount = itemCount + 1
#if itemCount != 0:
cn.commit()
cn.close
#使用上面的两个函数
def importData(path):
createDataBase()
database = sqlite3.connect("students.db")
readExcel(path, database)
#显示学生名单里的信息
def show( filename):
conn = sqlite3.connect( filename)
c = conn.cursor()
print("\nThe %s information is as follows:" % filename)
cursor = c.execute("SELECT code, name, Chinese, Mathematic, English from TB_STUDENTS")
for row in cursor:
print("CODE = ", row[0])
print("NAME = ", row[1])
print("Chinese = ", row[2])
print("Mathematic = ", row[3])
print("English = ", row[4], "\n")
print("\n\t\tEND")
conn.close()
path = input("Please enter the excel file's name:")
importData(path)
show("students.db")