python读取mysql结果写入Excel

代码环境 python3

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pymysql
import xlwt
import time
curr_date=time.strftime("%Y-%m-%d", time.localtime()) 

# 结果文件存放位置
rest_file_path="C:\\Desktop\\"
# 参数 mysql表名,读取字段,要读取字段值,要提取的数据量
def export_excel(table_name,product,product_name,num):
    # 数据量连接信息
    conn = pymysql.connect(user='root',host='127.0.0.1',port=3306,passwd='root',db='test',charset='utf8')
    cur = conn.cursor()
   # 设置读取数据的SQL
    sql = "select * from %s where %s = '%s' ;" %(table_name,product,product_name)
    # 设置存放结果文件名
    rest_file_path_1=(rest_file_path+curr_date+'%s'+'_'+'%s'+'.xls') %(num,product_name)
    #读取数据
    cur.execute(sql)
    fileds = [filed[0] for filed in cur.description]
    all_date = cur.fetchall() #所有数据
    #for result in all_date:
     #   print(result)
    #写excel
    book = xlwt.Workbook() #创建一个book
    sheet = book.add_sheet('result') #创建一个sheet表
    for col,filed in enumerate(fileds):
        sheet.write(0,col,filed)
    #从第一行开始写
    row = 1
    for data in all_date:
        for col,filed in enumerate(data):
            sheet.write(row,col,filed)
        row += 1
    book.save(rest_file_path_1)

if __name__ == '__main__':
    export_excel('res_20210209','产品','护手霜',9587)
    print("结束")
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值