flask 导出数据写入execl


前言

  • 导出数据写入ececl的方法有很多种,随个人喜好选择,可以采用保存文件的方式,也可以采用流方式。
  • 重点在于要更改响应头类型使其支持中文名称输出

代码实现

@api.route('/download')
def download():
    data = Case.query.filter_by().all()
    # 创建IO对象
    output = BytesIO()
    # 写excel
    workbook = xlsxwriter.Workbook(output)  # 先创建一个book,直接写到io中

    sheet = workbook.add_worksheet('sheet1')
    fileds = ['用例编号', '测试项', '测试分项', '测试点', '前置条件',
              '测试方法和步骤', '预期结果', '是否通过', '实际结果',
              '设计日期', '结论日期', '测试人员']

    # 写入数据到A1一列
    sheet.write_row('A1', fileds)

    # 遍历有多少行数据
    for i in range(len(data)):
        # 遍历有多少列数据
        for x in range(len(fileds)):
            key = [key for key in data[i].keys()]
            sheet.write(i + 1, x, data[i][key[x]])
            log.info('当前行:{}  当前列:{}  数据:{}'.format(str(i), str(x), data[i][key[x]]))
    workbook.close()  # 需要关闭
    output.seek(0)  # 找到流的起始位置
    resp = make_response(output.getvalue())
    basename = '测试用例.xlsx'

    # 转码,支持中文名称
    resp.headers["Content-Disposition"] = "attachment; filename*=UTF-8''{utf_filename}".format(
        utf_filename=quote(basename.encode('utf-8'))
    )

    resp.headers['Content-Type'] = 'application/x-xlsx'
    return resp


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM