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

人走茶凉 提交于 2020-01-12 14:54:28

问题


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


回答1:


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.




回答2:


You could try something like...

import xlrd

def newopen(fileobject, modes):
    return fileobject

oldopen = __builtins__.open
__builtins__.open = newopen
InputWorkBook = xlrd.open_workbook(fileobject)
__builtins__.open = oldopen

You may have to wrap the fileobject in StringIO if it isn't already a file handle.



来源:https://stackoverflow.com/questions/11955300/how-to-read-excel-files-from-a-stream-not-a-disk-backed-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!