当前位置:Gxlcms > 数据库问题 > pandas把读取sql的结果写入到excel文件

pandas把读取sql的结果写入到excel文件

时间:2021-07-01 10:21:17 帮助过:6人阅读

encoding: utf-8 import time import pandas as pd import pymysql def getrel(sql): ‘‘‘ 连接mysql数据库,根据条件查询出来我们所需要数据 :return: 根据条件从sql查询出来的数据 ‘‘‘ conn = pymysql.connect(host=‘localhost‘, user=‘root‘, password=‘123‘, db=‘db_test‘, charset=‘utf8mb4‘) cur = conn.cursor() cur.execute(sql) # 输入要查询的SQL rel = cur.fetchall() cur.close() conn.close() return rel def getxlsx(rel): ‘‘‘ 把从数据库中查询出来的数据写入excel文件 :param rel: :return: ‘‘‘ file_name = time.strftime(‘%Y-%m-%d‘) + ‘.xlsx‘ dret = pd.DataFrame.from_records(list(rel)) # mysql查询的结果为元组,需要转换为列表 dret.to_excel(file_name, index=False, header=("平台货号", "商品名称", "售价")) # header 指定列名,index 默认为True,写行名 if __name__ == ‘__main__‘: sql = ‘select goods_commonid,goods_name,goods_price from mall_goods_common where store_id=110 and set_new_time>1560182400;‘ rel = getrel(sql) getxlsx(rel)

 2.使用xlwt模块

import pymysql
import xlwt

def get_sel_excel(sql):
    ‘‘‘
    连接mysql并把查询出来的数据写入excel表格
    :param sql:
    :return:
    ‘‘‘
    conn = pymysql.connect(
        host="localhost",
        port=3306,
        user="root",
        passwd="123",
        db="db_test",
        charset="utf8mb4"
    )

    # 建立游标
    cursor = conn.cursor()
    print("开始查询表!")
    # 执行sql语句
    cursor.execute(sql)
    # 获取查询到结果
    res = cursor.fetchall()
    print(res)
    w_excel(res)


def w_excel(res):
    ‘‘‘
    把数据写入excel表格中
    :param res:
    :return:
    ‘‘‘
    book = xlwt.Workbook()  # 新建一个excel
    sheet = book.add_sheet(‘vehicle_land‘)  # 新建一个sheet页
    title = [‘平台货号‘, ‘商品名称‘, ‘售价‘]
    # 写表头
    i = 0
    for header in title:
        sheet.write(0, i, header)
        i += 1

    # 写入数据
    for row in range(1, len(res)):
        for col in range(0, len(res[row])):
            sheet.write(row, col, res[row][col])
        row += 1
    col += 1
    book.save(‘vehicle_land.xls‘)
    print("导出成功!")


if __name__ == "__main__":
    sql = ‘select goods_commonid,goods_name,goods_price from mall_goods_common where store_id=110 and set_new_time>1560182400;‘
    get_sel_excel(sql)

 

pandas把读取sql的结果写入到excel文件

标签:读取   encoding   cal   _id   成功   res   mysql数据库   user   表头   

人气教程排行