簡體   English   中英

使用 openpyxl 庫從 HTTP 響應解析 xlsx 表

[英]Parsing xlsx sheet from HTTP response using openpyxl library

我正在編寫一個測試用例來測試 Excel 表解析。 我嘗試使用 openpyxl 將 response.content 解析為對象列表。 我已經從響應頭中提取了文件名並轉換為類似文件的對象。 load_workbook() 不接受文件名。

def test_export_timesheet(self):
        change_url = '/admin/core/timesheet/'

        #response contains the generated file using openpyxl
        response = self.client.post(change_url, {'action': 'export_xlsx', '_selected_action': [x.id for x in timesheets]})

    content = response._headers.get('content-disposition')[1]
    start = content.find('=') + 1
    end = content.find('.xlsx')
    content_path = (content[start:end]+'.xlsx')

    #Passing file like object
    wb = load_workbook(BytesIO(filename="'"+content_path+"'"))
    ws = wb.get_sheet_by_name(name="'" + content[start:end] + "'")
    for row in ws.iter_rows():
        for cell in row:
            print cell.value

基本上我試圖驗證我的測試用例中文件的內容。 有沒有辦法做到這一點?

# response contains the generated file using openpyxl
response = self.client.post(change_url, ・・・・・

當你得到上面的響應時,“response.content”是字節類型的,所以你可以用 BytesIO 將它加載到緩沖區中。 從上面繼續寫:

from io import BytesIO
file_like_object = BytesIO(response.content)
(from openpyxl import load_workbook) # if this line is needed...
wb = load_workbook(file_like_object)

現在您可以使用這個“wb”進行一般的 openpyxl 操作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM