TypeError:预期的str,字节或os.PathLike对象,而不是FieldFile

问题描述 投票:0回答:2

我有这些excel工作表,这些是我从django rest框架的queryset中获取的。我将其转换为列表,并希望处理excel文件。在读取它之前我是否需要将其存储在我的应用程序中的某个位置,还是将其存储为变量并可以正常工作。什么是实现此目的的最佳方法?我尝试做的是这个,但似乎没有用。

excel_data =list(ExcelFiles.objects.all())
    print("excel_data", excel_data)
    for item in excel_data:
        print("item id ", item.id)
        print("item.company is ", item.company)
        print("item again", item.plan_type)
        print("item.excel is ", item.excelFile)
        print("item.status is" ,item.status)
        if item.status == False:
            if hasattr(item,'excelFile'):
                print(item.excelFile)
                excel_sheet=item.excelFile
                wb = xlrd.open_workbook(excel_sheet)// error occurs here
                sheet = wb.sheet_by_index(0)
                print("sheet", sheet)

我正在使用xlrd。

python django excel
2个回答
0
投票

我们不知道ExcelFiles.objects.all()里面是什么,也没有错误。我会说您可以做两件事:

  1. 检查item.excelFile是什么,它是链接吗?由于您不想保存它,因此最好是指向该文件的链接。

  2. [xlrd应该具有从链接读取的功能,但必须为URL内容,您可以尝试:

import requests
import xlrd
import urllib

link = 'https://raw.githubusercontent.com/SheetJS/test_files/a9c6bbb161ca45a077779ecbe434d8c5d614ee37/AutoFilter.xls'
file_name, headers = urllib.request.urlretrieve(link)
print (file_name)
workbook = xlrd.open_workbook(file_name)
print (workbook)

资源:Open an excel from http website using xlrd


0
投票

FieldFile是用于访问服务器上存储的文件的代理对象。从docs,FieldFile.name

文件名,包括从相关FileField的存储根开始的相对路径。

因此您可以简单地将路径传递到文件:

excel_sheet=item.excelFile
wb = xlrd.open_workbook(excel_sheet.name) # pass the path to the file instead
© www.soinside.com 2019 - 2024. All rights reserved.