How to read Excel files from a stream (not a disk-backed file) in Python?

Sushan Ghimire picture Sushan Ghimire · Aug 14, 2012 · Viewed 9.8k times · Source

XLRD is installed and tested:

>>> import xlrd
>>> workbook = xlrd.open_workbook('Sample.xls')

When I read the file through html form like below, I'm able to access all the values.

  xls_file = request.params['xls_file']
  print xls_file.filename, xls_file.type

I'm using Pylons module, request comes from: from pylons import request, tmpl_context as c

My questions:

  1. Is xls_file read through requst.params an object?
  2. How can I read xls_file and make it work with xlrd?

Update:

The xls_file is uploaded on web server, but the xlrd library expects a filename instead of an open file object, How can I make the uploaded file to work with xlrd? (Thanks to Martijn Pieters, I was being unable to formulate the question clearly.)

Answer

Rufus Pollock picture Rufus Pollock · Jan 19, 2013

xlrd does support providing data directly without a filepath, just use the file_contents argument:

xlrd.open_workbook(file_contents=fileobj.read())

From the documentation:

file_contents – A string or an mmap.mmap object or some other behave-alike object. If file_contents is supplied, filename will not be used, except (possibly) in messages.