Carlos Aguni

Highly motivated self-taught IT analyst. Always learning and ready to explore new skills. An eternal apprentice.


Django download pandas as excel

16 Sep 2021 »

https://stackoverflow.com/questions/56407199/django-pandas-dataframe-download-as-excel-file

from django.http import HttpResponse
from io import BytesIO

def some_view(request):
    with BytesIO() as b:
        # Use the StringIO object as the filehandle.
        writer = pd.ExcelWriter(b, engine='xlsxwriter')
        df.to_excel(writer, sheet_name='Sheet1')
        writer.save()
        # Set up the Http response.
        filename = 'django_simple.xlsx'
        response = HttpResponse(
            b.getvalue(),
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
        return response

https://davidwalsh.name/javascript-download

function download(){
    downloadFile(
        "<url>", 
        "file.xlsx",
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
}
function downloadFile(data, fileName, type="text/plain") {
  // Create an invisible A element
  const a = document.createElement("a");
  a.style.display = "none";
  document.body.appendChild(a);

  // Set the HREF to a Blob representation of the data to be downloaded
  //a.href = window.URL.createObjectURL(
  //  new Blob([data], { type })
  //);
  a.href = data

  // Use download attribute to set set desired file name
  a.setAttribute("download", fileName);

  // Trigger the download by simulating click
  a.click();

  // Cleanup
  window.URL.revokeObjectURL(a.href);
  document.body.removeChild(a);
}