• Django动态下载文件


    前台提交查询条件,下载符合条件的EXCEL数据文件,后端视图中使用 xlwt 库来返回,如:

    objs = Units.objects.all()
    # 创建 Workbook 时,如果需要写入中文,请使用 utf-8 编码,默认是 unicode 编码。
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('配件价格')
    ws.write(0, 0, '配件编号')
    ws.write(0, 1, '配件名称')
    ws.write(0, 2, '配件价格')
    ws.write(0, 3, '商场')
    excel_row = 1
    for obj in objs:
        ws.write(excel_row, 0, obj.unitid)
        ws.write(excel_row, 1, obj.unitname)
        ws.write(excel_row, 2, obj.price)
        ws.write(excel_row, 3, obj.marketid)
        excel_row = excel_row + 1
    # ------ 开始:这段代码可以用下面注释段替代,都是本应保存为文件格式的改成保存为数据流,以便返回前端下载
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=example.xls'
    wb.save(response)
    return response
    # ------ 结束
    """
    sio = StringIO.StringIO()
    wb.save(sio)
    response = HttpResponse(sio.getvalue(),content_type='application/vnd.ms-excel') 
    response['Content-Disposition'] = 'attachment; filename=test.xls'          
    return response
    """ 
  • 相关阅读:
    办公自动化15-一次性生成多层目录
    小技巧1-查看excel中工作表(sheet)的个数
    LaTex 公式编辑
    Cpp 学习网站
    函数的凹凸性
    二项分布
    函数间断点
    霍夫丁(Hoeffding)不等式
    数域
    马尔可夫(Markov)不等式
  • 原文地址:https://www.cnblogs.com/tianyajuanke/p/4048844.html
Copyright © 2020-2023  润新知