Fork me on GitHub

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
    )

posted @   是阿凯啊  阅读(803)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示