django 返回excel文件数据给前端下载

问题: django 返回excel文件无数据

解决:再view试图中返回时,添加如下选项

# 设置HttpResponse的类型
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment;filename={0}_{1}.xls'.format(executionCase_obj.id, int(time.time()))
response['Access-Control-Expose-Headers'] = 'Content-Disposition'  # (可不选)网关 跨域获取  Content-Disposition
output = write_old_driven_data(excel_data_list = [[1,2,3],[4,5,6]])
response.write(output.getvalue())

 

import xlwt

def write_data(excel_data_list, sheet_name='Sheet1'):
        """将数据写入下载的表中"""
        workbook = xlwt.Workbook(encoding='utf-8')
        worksheet = workbook.add_sheet(u'{}'.format(sheet_name))
        for row, row_data in enumerate(excel_data_list):
            for col, cell_data in enumerate(row_data):
                worksheet.write(row, col, cell_data)
                worksheet.col(col).width = 256 * 20
        # 写出到IO, 用于返回给前端excel文件下载
        import io
        output = io.BytesIO()
        workbook.save(output)
        output.seek(0)
        return output

 

你可能感兴趣的:(python)