Python web实现Excel数据下载

环境

python3;flask;

关键代码

import pandas
from io import BytesIO

def trans_record_data_to_io(data, rename_dict, col_order):
    """
    将列表数据转为excel的io对象
    rename_dict:{"col1": "列1", "col2": "列2"}
    col_order: ["列1", "列2"]
    """
    file = BytesIO()
    df = pandas.DataFrame(data)
    df.rename(columns=rename_dict, inplace=True)
    writer = pandas.ExcelWriter(file, engine='xlsxwriter')
    df.to_excel(writer, index=False, columns=col_order)
    writer.save()  # 这个save不会落盘
    return file.getvalue()

@bp.route('download', methods=['GET'])
def download():
    data = [{"col1": 1,  "col2": 2}]
    file_io_value = trans_record_data_to_io(data ,
        {"col1": "手机号", "col2": "姓名"},                
        ["姓名", "手机号"]
    )
    file_name = str(datetime.now())[:19] + ".xlsx"
    return Response(
        file_io_value, mimetype="application/octet-stream",
        headers={"Content-Disposition": "attachment;filename={0}".format(file_name)}
    )

优化

样例使用的是pandas这个包,有点大财小用。建议普通项目用excel专用包即可。

你可能感兴趣的:(Python web实现Excel数据下载)