码迷,mamicode.com
首页 > 其他好文 > 详细

flask通过内存导出excel

时间:2020-11-18 12:34:05      阅读:3      评论:0      收藏:0      [点我收藏+]

标签:转换   def   创建   excel导出   cat   出生日期   user   ide   error   

使用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
    )

flask通过内存导出excel

标签:转换   def   创建   excel导出   cat   出生日期   user   ide   error   

原文地址:https://www.cnblogs.com/xujunkai/p/13964731.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!