一、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)