简体   繁体   English

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

[英]How to export a xlsx file written with xlsxwriter

I have written some data in xlxs file with help of xlsxwriter I want to export it so that it can be downloaded how is this possible 我已经在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

This is my method but I am getting a file which is empty and could not be opened 这是我的方法,但是我得到的文件为空并且无法打开

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

Just try this. 尝试一下。

content-type you have used is for xls files. 您使用的content-type用于xls文件。

Can you try this instead of your code. 您可以尝试用它代替代码吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM