将 unicode 二进制数据作为参数传递给 XLRD 的 open_workbook 方法

Pass unicode binary data as a parameter for XLRD's open_workbook method

我想将 unicode 二进制数据作为 XLRD open_workbook 的参数 (file_contents) 传递。数据文件类型为.xls.

来自 article 的文档。

open_workbook(filename=None, logfile=sys.stdout, verbosity=0, pickleable=True, use_mmap=USE_MMAP, file_contents=None, encoding_override=None, formatting_info=False, ) 

file_contents
... as 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.

这里是 source code.

我试过这样做:

input = StringIO.StringIO()
input.write(vals['data'])

book = xlrd.open_workbook(file_contents=input.getvalue())

但是出现错误:

raise XLRDError('Unsupported format, or corrupt file: ' + msg)
XLRDError: Unsupported format, or corrupt file: Expected BOF record; found '0M8R4KGx'

我该怎么办?

我注意到您的数据以字符串 0M8R4KGx 开头。我进一步注意到 base64.decodestring('0M8R4KGx') 产生 \xd0\xcf\x11\xe0\xa1\xb1,这是 XLS 文件的前几个字节。

vals['data']中的字符串是base64编码的字符串。在将它写入文件之前,您必须先对其进行解码,如下所示:

input.write(base64.decodestring(vals['data']))

input.write(vals['data'].decode('base64'))

参考: