Python | Python+xlrd+xlwt realizes the import of excel file data into the database and the export of data from the database into excel (the code is elegant and easy to understand)

I learned an article about using java to operate excel, but after all, java is more rigorous, and it is a little cumbersome to implement. Python and excel are the real CPs that achieve the same function, with less code, and easy-to-understand syntax.

SpringBootMybatis+poi+Thymeleaf realizes the import of excel file data into the database and the export of data from the database into excel (detailed)
https://blog.csdn.net/y1534414425/article/details/106665202

One, Package

  1. pymysql Used to connect to the database
  2. xlrd Extended tool for reading Excel
  3. xlwt Extended tool for writing Excel files

Two, import excel into the database

import pymysql
import xlrd

# 打开xls文件
data = xlrd.open_workbook('C:\\Users\\Jonsson\\Desktop\\123.xlsx')
# 打开第一张表
table = data.sheets()[0]
# 获取表的行数
nrows = table.nrows
# 打开数据库连接
db = pymysql.connect(host='localhost',
                     port=3306,
                     user='root',
                     password='123456',
                     database='excel',
                     charset='utf8')
# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
# 循环逐行打印
for i in range(nrows):
    # 跳过第一行
    if i == 0:
        continue
    values = "'%s',%d,'%s','%s'" % (
        table.cell_value(i, 1), table.cell_value(i, 2), table.cell_value(i, 3), table.cell_value(i, 4))
    # 定义sql
    sql = """
    insert into car(`name`,`price`,`colour`,`brand`) values(%s)
    """ % values
    print(sql)
    try:
        # 使用execute()方法执行SQL查询
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
    except Exception as e:
        # 打印异常
        print(e)
        # 如果发生错误则回滚
        db.rollback()
# 关闭数据库连接
db.close()

Three, export the database to excel

import pymysql
import xlwt

# 打开数据库连接
db = pymysql.connect(host='localhost',
                     port=3306,
                     user='root',
                     password='123456',
                     database='excel',
                     charset='utf8')
# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
# 定义sql
sql = "select * from car"
try:
    # 使用execute()方法执行SQL查询
    cursor.execute(sql)
    # 打印输出结果
    data = cursor.fetchall()
    print(data)
    # 创建一个workbook 设置编码
    workbook = xlwt.Workbook(encoding='utf-8')
    # 创建一个worksheet
    worksheet = workbook.add_sheet('car')
    # 写入excel 参数对应 行, 列, 值
    for i in range(len(data)):
        # 第一行用于写入表头
        if i == 0:
            worksheet.write(i, 0, '主键(id)')
            worksheet.write(i, 1, '名称(name)')
            worksheet.write(i, 2, '价格(price)')
            worksheet.write(i, 3, '颜色(colour)')
            worksheet.write(i, 4, '品牌(brand)')
            continue
        for j in range(len(data[i])):
            worksheet.write(i, j, '%s' % data[i][j])
    # 保存
    workbook.save('C:\\Users\\Jonsson\\Desktop\\result.xls')
except Exception as e:
    # 打印异常
    print(e)
    # 如果发生错误则回滚
    db.rollback()
# 关闭数据库连接
db.close()

Fourth, the database script

DROP TABLE IF EXISTS `car`;
CREATE TABLE `car` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(255) DEFAULT NULL COMMENT '名称',
  `price` int(11) DEFAULT NULL COMMENT '价格',
  `colour` varchar(255) DEFAULT NULL COMMENT '颜色',
  `brand` varchar(255) DEFAULT NULL COMMENT '品牌',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=99 DEFAULT CHARSET=utf8 COMMENT='汽车';
LOCK TABLES `car` WRITE;
INSERT INTO `car` VALUES (85,'东风',150,'黑色','东风'),(86,'丰田',100,'白色','丰田'),(87,'本田',120,'蓝色','本田'),(88,'东风',150,'黑色','东风'),(89,'丰田',100,'白色','丰田'),(90,'本田',120,'蓝色','本田'),(91,'东风',150,'黑色','东风'),(92,'东风',150,'黑色','东风'),(93,'丰田',100,'白色','丰田'),(94,'本田',120,'蓝色','本田'),(95,'东风',150,'黑色','东风'),(96,'丰田',100,'白色','丰田'),(97,'本田',120,'蓝色','本田'),(98,'东风',150,'黑色','东风');
UNLOCK TABLES;

Five, effect

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/y1534414425/article/details/106688833