• Python从数据库取数据到Excel


    工具脚本---可以直接使用

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Time    : 2020/12/2 21:47
    # @Author  : Administrator
    # @File    : db_excel.py
    import os
    import xlwt
    import pymysql
    import datetime
    
    
    class MysqlToExcel(object):
        def __init__(self):
            self.host = '127.0.0.1'
            self.user = 'root'
            self.passwd = 'root'
            self.db_name = 'world'
            self.port = 3306
            self.file_name = 'data.xls'
    
        def get_query_results(self):
            sql = "select * from world.city;"
    
            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 get_maxlength(self, value, col):
            """
        获取value最大占位长度,用于确定导出的xlsx文件的列宽
        col : 表头,也参与比较,解决有时候表头过长的问题
        """
            # 长度列表
            len_list = []
            # 表头长度
            width = 256 * (len(col) + 1)
            len_list.append(width)
    
            # 数据长度
            if len(value) >= 10:
                width = 256 * (len(value) + 1)
                len_list.append(width)
    
            return max(len_list)
    
        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)
    
            # 第一行结果
            row0 = result[0]
            # 列字段
            column_names = list(row0)
    
            # 写第一行,也就是列所在的行
            for i in range(0, len(row0)):
                sheet1.write(0, i, column_names[i])
    
            # 写入多行
            # 行坐标,从第2行开始,也是1
            for row_id in range(1, len(result) + 1):
                # 列坐标
                for col_id in range(len(column_names)):
                    # 写入的值
                    value = result[row_id - 1][column_names[col_id]]
                    # 判断为日期时
                    if isinstance(value, datetime.datetime):
                        value = result[row_id - 1][column_names[col_id]].strftime('%Y-%m-%d %H:%M:%S')
    
                    # 获取表格对象
                    col = sheet1.col(col_id)
                    if value:
                        if isinstance(value, int):
                            value = str(value)
    
                        # 获取宽度
                        width = self.get_maxlength(value, column_names[col_id])
    
                        # 设置宽度
                        col.width = width
                    # 写入表格
                    sheet1.write(row_id, col_id, value)
    
            # 保存文件
            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()

     

  • 相关阅读:
    Orchard Oracle 支持
    讽刺的是,我在linux下使用最多的命令,竟然是windows的
    学习bash
    提高分布式环境中程序启动性能的一个方法
    MQTT X v1.4.1 正式发布
    社区力量|因为 EMQ,他上了微博热搜
    不止是现在,更关注未来:EMQ 携手高校加强物联网人才培养
    EMQ 助力西安增材制造国家研究院打造增材智能车间平台
    Kuiper 1.0.1 正式发布
    MQTT X v1.4.0 正式发布
  • 原文地址:https://www.cnblogs.com/wzhqzm/p/14076738.html
Copyright © 2020-2023  润新知