0

我可以直接从 HTTP 位置读取以与 xlrd 一起使用吗?

我尝试了以下方法:

import ntlm, urllib2
url = 'http://myurl/file.xls'
passman.add_password(None, url, login, password)
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)
opener = urllib2.build_opener(auth_NTLM)
sock = urllib2.urlopen(url)
content = sock.read()

并具有ReadFromExcel读取 Excel 文件并返回一些数据的函数,但它无法从内容中读取。

ReadFromExcel(content) 
    book = xlrd.open_workbook(filename)
  File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 400, in open_workbook
    f = open(filename, "rb")
TypeError: file() argument 1 must be encoded string without NULL bytes, not str

有任何想法吗?

4

1 回答 1

3

您应该传递文件名而不是文件的内容:

import os
import tempfile

with tempfile.NamedTemoraryFile(suffix='.xls') as file:
    file.write(content)
    file.delete = False

try:
    result = ReadFromExcel(file.name)
finally:
    os.remove(file.name)

或使用file_contents参数

于 2013-03-11T19:44:09.143 回答