现有一个用户表,需要将表数据写入到excel中。

环境说明

mysql版本:5.7

端口:3306

数据库:test

表名:users

 

表结构如下:

CREATE TABLE `users` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) COLLATE utf8mb4_bin NOT NULL COMMENT '用户名',
  `password` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '密码',
  `phone` varchar(20) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '手机号',
  `email` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '邮箱',
  `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

 

插入3行数据

INSERT INTO `test`.`users` (`id`, `username`, `password`, `phone`, `email`, `create_time`) VALUES ('1', 'xiao', '123', '12345678910', '123@qq.com', '2020-04-10 01:22:07');
INSERT INTO `test`.`users` (`id`, `username`, `password`, `phone`, `email`, `create_time`) VALUES ('2', 'zhang', '123', '12345678910', '123@qq.com', '2020-04-10 01:22:07');
INSERT INTO `test`.`users` (`id`, `username`, `password`, `phone`, `email`, `create_time`) VALUES ('3', 'lisi', '123', '12345678910', '123@qq.com', '2020-04-10 01:22:07');

 

二、基本写法

安装模块

pip3 install xlwt pymysql

 

test_excel.py

#!/usr/bin/env python3
# coding: utf-8
import os
import xlwt
import pymysql
import datetime

class MysqlToExcel(object):
    def __init__(self):
        self.host = '10.212.21.92'
        self.user = 'root'
        self.passwd = 'abcd1234'
        self.db_name = 'test'
        self.port = 3306
        self.file_name = 'data.xls'

    def get_query_results(self):
        sql = "select * from test.users"

        conn = pymysql.connect(
            host=self.host,
            user=self.user,
            passwd=self.passwd,
            port=self.port,
            database=self.db_name,
            charset='utf8',
            cursorclass=pymysql.cursors.DictCursor
        )
        cur = conn.cursor()  # 创建游标
        cur.execute(sql)  # 执行sql命令
        result = cur.fetchall()  # 获取执行的返回结果
        # print(result)
        cur.close()
        conn.close()  # 关闭mysql 连接
        return result

    def generate_table(self):
        """
        生成excel表格
        :return:
        """
        # 删除已存在的文件
        if os.path.exists(self.file_name):
            os.remove(self.file_name)

        result = self.get_query_results()
        # print(result)
        if not result:
            print("查询结果为空")
            return False

        # 创建excel对象
        f = xlwt.Workbook()
        sheet1 = f.add_sheet('Sheet1', cell_overwrite_ok=True)

        # 列字段
        column_names = ['id','username','password','phone','email']

        # 写第一行,也就是列所在的行
        for i in range(0, len(column_names)):
            sheet1.write(0, i, column_names[i])

        # 写入多行
        num = 0  # 计数器
        for i in result:
            sheet1.write(num + 1, 0, i['id'])
            sheet1.write(num + 1, 1, i['username'])
            sheet1.write(num + 1, 2, i['password'])
            sheet1.write(num + 1, 3, i['phone'])
            sheet1.write(num + 1, 4, i['email'])
            # 日期转换为字符串
            value = i['create_time'].strftime('%Y-%m-%d %H:%M:%S')
            sheet1.write(num + 1, 5, value)

            num += 1  # 自增1

        # 保存文件
        f.save(self.file_name)

        # 判断文件是否存在
        if not os.path.exists(self.file_name):
            print("生成excel失败")
            return False

        print("生成excel成功")
        return True

if __name__ == '__main__':
    MysqlToExcel().generate_table()
View Code

相关文章: