Home » excel » python – Django upload excel file, process with pandas, download as csv

python – Django upload excel file, process with pandas, download as csv

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m running Django on a localhost (Later to run on a LAN) where the idea is I can go onto the webpage, click a button where you’re prompted to select an excel file from your computer. Pandas will do work on said excel file and Django/Pandas will make excel file of this Pandas data frame as a download prompt.

I’ve got Django running and using the code below from the module ‘Django-Excel’ does the basics of what I want. Excel file in —> excel file out, no saving the file to a database or anything just keeping it in the memory. However, I cannot find a way to shoehorn Pandas into it. The main problem I have is I’m unsure how to return an excel file using Pandas. I’ve been using ‘.to_excel()’ in my offline python code, however, haven’t found a way to use it in a localhost running Django. I’m sure I’m missing something really simple but I just can’t get it.

Maybe if someone could show a simple example of say, uploading an excel, pandas will multiply a column of numbers in the excel by 2, new excel is outputted to read/save.

from django.shortcuts import render, redirect
from django.http import HttpResponseBadRequest, HttpResponse
from _compact import JsonResponse
from django import forms
import django_excel as excel
from polls.models import Question, Choice


class UploadFileForm(forms.Form):
file = forms.FileField()


# Create your views here.
def upload(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            filehandle = request.FILES['file']
            # do pandas here to filehandle/ put filehandle into a function 
            return excel.make_response(filehandle.get_sheet(), "csv",
                                       file_name="download")
    else:
        form = UploadFileForm()
    return render(
        request,
        'upload_form.html',
        {
            'form': form,
            'title': 'Excel file upload and download example',
            'header': ('Please choose any excel file ' +
                       'from your cloned repository:')
})

Thank you very much, sorry if this isn’t clear It’s my first time posting on this website, if you don’t understand what I’m asking for I’ll elaborate more.

How to&Answers:

I’ll upload my answer for anyone looking at this in the future 🙂

def uploads(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            kappa = request.FILES['file']
            # Do work on kappa/excel file here with Pandas
            output = io.BytesIO()
            writer = pd.ExcelWriter(output, engine='xlsxwriter')
            kappa.to_excel(writer, index=False)
            writer.save()
            output.seek(0)
            response = HttpResponse(output,
                                content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download'
        return response
else:
    form = UploadFileForm()
return render(request, 'upload_form.html', {'form': form})

I abandoned using ‘Django-excel’ and instead used ‘BytesIO’ from the io module. This has the bonus of not relying on a third-party module.
you’re able to write a Pandas dataframe to io.BytesIO() and then use that in your HttpResponse.