2012-10-14 66 views
6

我有一個用戶上傳文件到網站,我需要解析電子表格。這裏是我的代碼:打開電子表格返回InMemoryUploadedFile

input_file = request.FILES.get('file-upload') 
wb = xlrd.open_workbook(input_file) 

我不斷收到的錯誤是:

TypeError at /upload_spreadsheet/ 
coercing to Unicode: need string or buffer, InMemoryUploadedFile found 

爲什麼會發生什麼,我需要做的,解決這個問題?謝謝。

供參考,這是我在shell

>>> import xlrd 
>>> xlrd.open_workbook('/Users/me/dave_example.xls') 
<xlrd.Book object at 0x10d9f7390> 
+0

出於好奇,你能得到展開片的保持(例如,你在一個位置有用戶通過電子郵件發送給您?)。如果可能的話,將文件放在本地並驗證它是否沒有損壞會很有用。 – Dave

+0

@Dave - 不,不幸的是我不能那樣做。請參閱更新的問題。 – David542

回答

12

你可以轉儲InMemoryUploadedFile到一個臨時文件,打開該文件xlrd開幕之前。

try: 
    fd, tmp = tempfile.mkstemp() 
    with os.fdopen(fd, 'w') as out: 
     out.write(input_file.read()) 
    wb = xlrd.open_workbook(tmp) 
    ... # do what you have to do 
finally: 
    os.unlink(tmp) # delete the temp file no matter what 

如果你想保存在內存中的一切,嘗試:

wb = xlrd.open_workbook(filename=None, file_contents=input_file.read()) 
+0

磁盤寫入似乎沒有必要。沒有辦法如何避免它? –

+0

@PetrPeller:如果你有內存中的文件內容,你可以在調用'open_workbook'時使用'file_contents'參數;它是一個字符串(或者一個'mmap.mmap'對象或者其他類似行爲的對象)。如果提供了file_contents,則不會使用文件名,除了(可能)在消息中。 –

+0

我不得不使用像「wb = xlrd.open_workbook(**文件名=無**,file_contents = input_file.read())」正常工作 – kmonsoor

相關問題