使用django

时间:2015-10-24 13:20:30

标签: python django xlsxwriter

我正在尝试使用django下载使用xlsxwriter生成的xlsl文件。我之前已多次编写这样的代码,但不是xlsxwriter(使用csvwriter)并且它工作得很好。但在这种情况下,当我下载文件时,它总是空的。但是文件系统上的文件不是。

这是我的观看代码:

def download_xls(self, request):
    os.chdir('/tmp')
    xls_name = re.sub('\s+', '_', "%s_%s_%s.xlsx" % (
        request.user.username.lower(),
        self.report.name.lower(),
        datetime.now().strftime('%y%m%d_%H%I%S')))

    workbook = xlsxwriter.Workbook(xls_name)
    worksheet1 = workbook.add_worksheet()
    worksheet2 = workbook.add_worksheet()

    worksheet1.write("A1", "hello1")
    worksheet2.write("A1", "hello2")

    workbook.close()
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-disposition'] = "attachment; filename=%s" % xls_name
    return response

这是文件系统上的文件:

-rw-r--r--  1 _www            wheel   5751 Oct 24 09:14 /tmp/admin_wafer_viz_151024_090900.xlsx

这是下载的文件:

-rw-------@   1 LarryMartell  staff      0 Oct 24 09:14 admin_wafer_viz_151024_090900.xlsx

任何人都可以看到我在这里做错的可能是愚蠢的事吗?

1 个答案:

答案 0 :(得分:2)

您需要将工作簿保存到响应中,以将实际文件放入HTTP响应中:

def download_xls(self, request):
    os.chdir('/tmp')
    xls_name = re.sub('\s+', '_', "%s_%s_%s.xlsx" % (
        request.user.username.lower(),
        self.report.name.lower(),
        datetime.now().strftime('%y%m%d_%H%I%S')))
    output = io.BytesIO()

    workbook = Workbook(output, {'in_memory': True})
    worksheet1 = workbook.add_worksheet()
    worksheet2 = workbook.add_worksheet()

    worksheet1.write("A1", "hello1")
    worksheet2.write("A1", "hello2")

    workbook.close()

    output.seek(0)

    response = HttpResponse(content_type='application/ms-excel')
    response['Content-disposition'] = "attachment; filename=%s" % xls_name

    return response

您还可以尝试xlwt包,这看起来更简单:

workbook.save(response)
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = "attachment; filename=%s" % xls_name

您可以在我的某个项目here

上看到一个示例