1. 程式人生 > 實用技巧 >flask通過記憶體匯出excel

flask通過記憶體匯出excel

使用Flask-excel匯出資料

  • 安裝:
pip install Flask-Excel
pip install pyexcel-xlsx  # 匯出xlsx
pip install pyexcel-xls   # 匯出xls
  • 註冊app
import flask_excel as excel

excel.init_excel(app)
# 如果不註冊會報錯:The view function did not return a valid response. The function either returned None or ended without a return statement.
  • 使用
@api.route("/ExportUser/<id_str>/", methods=["GET",], endpoint="export_user")
@admin_deco_required
def export_user(id_str):
    """
    匯出使用者列表
    :param id_str: 1,3,4,5,6,7
    :return:
    """
    institution_obj = Institution.query.filter_by(inid=g.user_id).first_or_404()
    if not id_str:
        raise NotFound(message=ResponseMessage.InvalidParameter)
    try:
        id_list = list(map(int, id_str.split(",")))
    except ValueError as e:
        logger.error(e)
        raise NotFound(message=ResponseMessage.InvalidParameter)
    # 查詢資料
    result = db.session.query(
        User.account_name.label("使用者名稱"),
        User.phone.label("手機號"),
        User.identity_code.label("身份證號"),
        User.real_name.label("真實姓名"),
        User.birth.label("出生日期"),
        User.gender.label("性別"),
        User.department.label("部門"),
        User.politicalStatus.label("政治面貌"),
        User.marriage.label("婚姻狀況"),
        User.address.label("住址"),
        User.educationalType.label("教育程度"),
        User.create_time.label("建立時間")
    ).filter(
        and_(
            User.id.in_(id_list),
            User.status == 1,
            User.institution_id == g.user_id
        )
    ).order_by(User.create_time.asc()).all()
    # 設定匯出檔名字
    xlsx_filname = "{}_{}.xlsx".format(institution_obj.institution_name, int(time.time()))
	# 返回excel 檔案, fmt_transform 為自己實現資料序列化轉換。
    return excel.make_response_from_query_sets(
        fmt_transform(result),
        column_names=[
            '使用者名稱',
            '手機號',
            '身份證號',
            '真實姓名',
            '出生日期',
            '性別',
            '部門',
            '政治面貌',
            '婚姻狀況',
            '住址',
            '教育程度',
            '建立時間',
        ],
        file_type='xlsx',
        file_name=xlsx_filname
    )