Python 将excel数据导入数据库

import xlrd
import pymysql


# 打开excel文件
def open_excel():
    try:
        book = xlrd.open_workbook("123.xlsx")  # 文件名,把文件与py文件放在同一目录下
    except:
        print("open excel file failed!")

    try:
        sheet = book.sheet_by_name("sheet1")  # execl里面的worksheet1
        return sheet
    except:
        print("locate worksheet in excel failed!")


# 连接数据库
try:
    db = pymysql.connect(host="127.0.0.1", user="root",
                         passwd="3105501510",
                         db="xiaoyang",
                         charset='utf8')
except:
    print("could not connect to mysql server")


def search_count():
    cursor = db.cursor()
    select = "select count(*) from tiku"  # 获取表中记录数
    cursor.execute(select)  # 执行sql语句
    line_count = cursor.fetchone()
    print("当前数据库中一共" + str(line_count[0]) + "条记录")


def insert_deta():
    sheet = open_excel()
    cursor = db.cursor()
    for i in range(1, sheet.nrows):  # 第一行是标题名,对应表中的字段名所以应该从第二行开始,计算机以0开始计数,所以值是1

        id = sheet.cell(i, 0).value  # 取第i行第0列
        _type = sheet.cell(i, 1).value  # 取第i行第1列,下面依次类推
        if _type == "单选":
            _type = 1
        elif _type == "多选":
            _type = 2
        elif _type == "判断":
            _type = 3
        else:
            _type = 0

        title = sheet.cell(i, 2).value
        option_a = sheet.cell(i, 3).value
        option_b = sheet.cell(i, 4).value
        option_c = sheet.cell(i, 5).value
        option_d = sheet.cell(i, 6).value
        answer = sheet.cell(i, 7).value
        page = sheet.cell(i, 8).value
        source = sheet.cell(i, 9).value

        value = (id, _type, title, option_a, option_b, option_c, option_d, answer, page, source)
        print(value)
        try:
            sql = "INSERT INTO tiku (id,type,title,option_a,option_b,option_c,option_d,answer,page,source)VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
            cursor.execute(sql, value)  # 执行sql语句
            db.rollback()
        except:
            print("SQL执行错误!")
            break
        
        db.commit()
    cursor.close()  # 关闭连接


# insert_deta()

print("ok ")
if __name__ == '__main__':
    search_count()
    insert_deta()
    db.close()  # 关闭数据

 

注意

在运用python中xlrd库读取.xlsx文件时报错,无法读取。这是由于当前python中的xlrd版本过高导致的,高版本下删除的对应的.xlsx读取方法。因此,只需要重装xlrd即可

pip3 install xlrd==1.2.0

 

 

微信关注

WeChat

 

本站为非盈利性站点,所有资源、文章等仅供学习参考,并不贩卖软件且不存在任何商业目的及用途,如果您访问和下载某文件,表示您同意只将此文件用于参考、学习而非其他用途。
本站所发布的一切软件资源、文章内容、页面内容可能整理来自于互联网,在此郑重声明本站仅限用于学习和研究目的;并告知用户不得将上述内容用于商业或者非法用途,否则一切后果请用户自负。
如果本站相关内容有侵犯到您的合法权益,请仔细阅读本站公布的投诉指引页相关内容联系我,依法依规进行处理!
作者:理想
链接:https://www.imyjs.cn/archives/443
THE END
二维码
Python 将excel数据导入数据库
import xlrd import pymysql # 打开excel文件……
<<上一篇
下一篇>>
文章目录
关闭
目 录