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>
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With