python读取mysql数据生成excel和html并发送指定邮箱

需求

由于业务需要,需读取mysql数据生成excel,并以附件的形式发送到指定邮箱,正文内容也以表格的形式进行数据展示

分析

采用pymysql进行mysql数据的读取,通过openpyxl处理读取的数据并写入excel,之后通过smtplib将相关数据文件发送到指定邮箱

实现

1.pymysql读取mysql表数据返回result

import pymysql

class MysqlCon():
    def __init__(self,host,user,password,database,charset):
        '''
        :param host: 主机名
        :param user: 用户名
        :param password: 密码
        :param database: 数据库名
        :param charset: 编码
        '''
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.charset = charset
        self.cursor = None
        self.connection = None

    def __enter__(self):
        self.connection = pymysql.connect(host=self.host, user=self.user
                                          ,password=self.password, database=self.database, charset=self.charset)
        self.cursor = self.connection.cursor()
        return self.cursor

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()


if __name__ == '__main__':
    host = 'mysql-test-test.test.local'
    username = 'test'
    password = 'test@test'
    database = 'test'
    charset = 'utf8'
    sql = 'select f1,f2,f3 from test'
    with MysqlCon(host,username,password,database,charset) as mycursor:
        mycursor.execute(sql)
        result = mycursor.fetchall()

2.openpyxl将读取的result转存excel

import os
from openpyxl import Workbook,load_workbook
from openpyxl.styles import Alignment
from openpyxl.utils import get_column_letter
import time
import logging

def create_xlsx_file(file_path,file_name):
    '''
    用于创建xlsx文件,存在
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值