Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening spreadsheet returns InMemoryUploadedFile

Tags:

python

django

I have a user uploading a file to a website and I need to parse the spreadsheet. Here is my code:

input_file = request.FILES.get('file-upload')
wb = xlrd.open_workbook(input_file)

The error I keep getting is:

TypeError at /upload_spreadsheet/
coercing to Unicode: need string or buffer, InMemoryUploadedFile found

Why is this happening and what do I need to do to fix it? Thank you.

For reference, this is how I open the file in the shell

>>> import xlrd
>>> xlrd.open_workbook('/Users/me/dave_example.xls')
<xlrd.Book object at 0x10d9f7390>
like image 365
David542 Avatar asked Oct 14 '12 21:10

David542


Video Answer


1 Answers

You can dump the InMemoryUploadedFile to a temp file before opening with xlrd.

try:
    fd, tmp = tempfile.mkstemp()
    with os.fdopen(fd, 'w') as out:
        out.write(input_file.read())
    wb = xlrd.open_workbook(tmp)
    ...  # do what you have to do
finally:
    os.unlink(tmp)  # delete the temp file no matter what

If you want to keep everything in memory, try:

wb = xlrd.open_workbook(filename=None, file_contents=input_file.read())
like image 77
Paulo Scardine Avatar answered Sep 22 '22 11:09

Paulo Scardine