Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.)

like image 904
Sushan Ghimire Avatar asked Aug 14 '12 15:08

Sushan Ghimire


1 Answers

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.

like image 104
Rufus Pollock Avatar answered Oct 11 '22 22:10

Rufus Pollock