Search code examples
pythondjangopyexcel

Pyexcel get records from excel upload


I'm trying to integrate pyexcel into a Django project and trying to follow the example on the docs.

I'm trying to replicate this functionality:

import pyexcel as pe
records = pe.iget_records(file_name="your_file.xls")
for record in records:
    print("%s is aged at %d" % (record['Name'], record['Age']))

How do I go about opening the records via a file upload. I've tried to do this with no luck:

if request.method == "POST":
    form = UploadFileForm(request.POST, request.FILES)
    records = pe.iget_records(file_name=request.FILES['file'])
    for record in records:
    ..

This line is bugging out: records = pe.iget_records(file_name=request.FILES['file'])

Edit: The seems to happen in the for loop and is:

IOError: Wrong file name

Solution

  • There is a get_records in the documentation.

    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        records = request.FILES['file'].get_records()
        for record in records:
        ..
    

    If you insist to use iget_record, you could try:

    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        file = request.FILES['file']
        file_type = file.name.split('.')[-1]
        records = pe.iget_records(file_stream=file, file_type=file_type)
        for record in records:
        ..