如何导出用xlsxwriter编写的xlsx文件

时间:2018-06-15 10:37:31

标签: python django

我在xlsxwriter的帮助下在xlxs文件中写了一些数据我想导出它以便可以下载它是如何实现的

def export(request,pk):
    import xlsxwriter

    product_resources = ProductType.objects.get(pk=pk)
    print(product_resources)
    attr = product_resources.product_attributes.all()
    r1=[]

    r1.append(str(product_resources))
    for i in range(0,len(attr)):
        r1.append(str(attr[i]))
    print(r1)
    if(request.GET):
        col=0
        row=0
        workbook = xlsxwriter.Workbook('Product.xlsx')
        worksheet = workbook.add_worksheet()
        for item in r1:
            worksheet.write_string(row,col, item)
            col+=1


        response = HttpResponse(content_type='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename="product.xlsx"'
        workbook.close()

        return response

这是我的方法,但我收到的文件是空的,无法打开

2 个答案:

答案 0 :(得分:1)

response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=product.xlsx"

试试吧。

您使用的内容类型是xls文件。

答案 1 :(得分:1)

你可以试试这个而不是你的代码。

def export(request,pk):
    import xlsxwriter

    output = io.BytesIO()

    workbook = xlsxwriter.Workbook(output,{'in_memory': True})
    workbook = xlsxwriter.Workbook(output, {'remove_timezone': True})

    product_resources = ProductType.objects.get(pk=pk)
    print(product_resources)
    attr = product_resources.product_attributes.all()
    r1=[]

    r1.append(str(product_resources))
    for i in range(0,len(attr)):
        r1.append(str(attr[i]))
    print(r1)
    if(request.GET):
        col=0
        row=0

        worksheet = workbook.add_worksheet()
        for item in r1:
            worksheet.write_string(row,col, item)
            col+=1

        output.seek(0)

        response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        response['Content-Disposition'] = "attachment; filename=product.xlsx"
        workbook.close()

        return response