代码环境 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("结束")