Django Pandas to http response (download file)

前端 未结 6 960
醉话见心
醉话见心 2020-12-29 06:36

Python: 2.7.11

Django: 1.9

Pandas: 0.17.1

How should I go about creating a potentially large xlsx file download? I\'m creating a xlsx file with panda

6条回答
  •  天命终不由人
    2020-12-29 07:07

    Just wanted to share a class-based view approach to this, using elements from the answers above. Just override the get method of a Django View. My model has a JSON field which contains the results of dumping a dataframe to JSON with the to_json method.

    Python version is 3.6 with Django 1.11.

    # models.py
    from django.db import models
    from django.contrib.postgres.fields import JSONField
    
    class myModel(models.Model):
        json_field = JSONField(verbose_name="JSON data")
    
    # views.py
    import pandas as pd
    from io import BytesIO as IO
    from django.http import HttpResponse
    from django.views import View
    
    from .models import myModel
    
    class ExcelFileDownloadView(View):
        """
        Allows the user to download records in an Excel file
        """
    
        def get(self, request, *args, **kwargs):
    
            obj = myModel.objects.get(pk=self.kwargs['pk'])
            excel_file = IO()
            xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter')
            pd.read_json(obj.json_field).to_excel(xlwriter, "Summary")
            xlwriter.save()
            xlwriter.close()
    
            excel_file.seek(0)
    
            response = HttpResponse(excel_file.read(),
                                    content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    
            response['Content-Disposition'] = 'attachment; filename="excel_file.xlsx"'
            return response
    
    # urls.py
    from django.conf.urls import url
    from .views import ExcelFileDownloadView
    
    urlpatterns = [
        url(r'^mymodel/(?P\d+)/download/$', ExcelFileDownloadView.as_view(), name="excel-download"),]
    

提交回复
热议问题