Flask下载文件接口,以excl表哥为例

一、response

        1、定义写入表哥的代码   

def create_excel_xls(path, sheet_name, value):
    index = len(value)  # 获取需要写入数据的行数
    workbook = xlwt.Workbook()  # 新建一个工作簿
    sheet = workbook.add_sheet(sheet_name)  # 在工作簿中新建一个表格
    for i in range(0, index):
        for j in range(0, len(value[i])):
            sheet.write(i, j, value[i][j])  # 像表格中写入数据(对应的行和列)
    workbook.save(path)  # 保存工作簿
    print("raffle.xls表格创建成功!")


def write_excel_xls_append(path, value):
    index = len(value)  # 获取需要写入数据的行数
    workbook = xlrd.open_workbook(path)  # 打开工作簿
    sheets = workbook.sheet_names()  # 获取工作簿中的所有表格
    worksheet = workbook.sheet_by_name(sheets[0])  # 获取工作簿中所有表格中的的第一个表格
    rows_old = worksheet.nrows  # 获取表格中已存在的数据的行数
    new_workbook = copy(workbook)  # 将xlrd对象拷贝转化为xlwt对象
    new_worksheet = new_workbook.get_sheet(0)  # 获取转化后工作簿中的第一个表格
    for i in range(0, index):
        for j in range(0, len(value[i])):
            new_worksheet.write(i + rows_old, j, value[i][j])  # 追加写入数据,注意是从i+rows_old行开始写入
    new_workbook.save(path)  # 保存工作簿
    print("raffle.xls表格【追加】写入数据成功!")

        接口实现

        


@app.route('/result/download', methods=['GET'])
def raffle_file():
    """
    下载抽中名单表格
    """
    book_name_xls = 'raffle.xls'
    sheet_name_xls = '答题中奖名单'
    value_title = [["问题", "答案", "区", "排", "坐", "时间"], ]
    Session = sessionmaker(bind=engine, autocommit=False)
    session = Session()
    audience = session.query(CfsResult.question, CfsResult.answer, CfsResult.part, CfsResult.row, CfsResult.seat, CfsResult.update_time).filter().all()
    session.close()
    create_excel_xls(book_name_xls, sheet_name_xls, value_title)
    write_excel_xls_append(book_name_xls, audience)
    
    
    # response实现
    fileData = open(book_name_xls, 'rb').read()
    response = app.make_response(fileData)
    response.headers["Content-Disposition"] = 'attachment; filename={}'.format(book_name_xls)
    response.headers["Content-Type"] = 'application/x-xlsx'
    return response

    # send_file实现
    return send_file(book_name_xls, as_attachment=True)

你可能感兴趣的:(flask,python,后端)