一、首先需要思考,我們在頁面導(dǎo)出excel,用python導(dǎo)出如何寫入文件的
封裝前需要確認python導(dǎo)出excel接口返回的是一個什么樣的數(shù)據(jù)類型
如下:我們先看下不對返回結(jié)果做處理,直接接收數(shù)據(jù)類型是一個對象,無法獲取返回值

此時我們需要對返回數(shù)據(jù)做處理,如下;
response.text # 響應(yīng)文本數(shù)據(jù)(字符串)

把返回的數(shù)據(jù)類型變成了dict,response.json()** 這樣就方便我們按照字典的操作去拿數(shù)據(jù)**
但是 我們現(xiàn)在的操作是要獲取導(dǎo)出文件的數(shù)據(jù),導(dǎo)出excel是一個二進制文件:
response.content # 響應(yīng)返回的內(nèi)容(二進制)
接下來我們按思路response.content方法來把這個二進制文件寫入excel中:
二、如下封裝:
class Export:
    """
    導(dǎo)出域
    """
    def __init__(self, token):
        self.token = token
        self.headers = {
                'Authorization': self.token,
                'Content-Type': 'application/json;charset=UTF-8'
        }
        
        ```
def export_sku_excel(self, payload, path):
    """
            商品:商品明細導(dǎo)出
            """
    url = f'{HOST}/api/v1/commodity/exportSKU'
    res = client.post(url=url, json=payload, verify=False, headers=self.headers)
    resp = res.content
    with open(path, 'wb') as f:  # 第一個參數(shù)是保存文件路徑,不加路徑就是當前路徑
        if res.status_code == 200:
            return f.write(resp)
        else:
            return False
如上,先接收二進制文件,然后使用操作excel方法‘wb’寫入二進制文件
以上寫入文件后,測試過程我們需要再讀取文件數(shù)據(jù)來斷言,如下:
class ExcelMethod:
    def __init__(self, filename):
        self.filename = filename
    def read_excel(self, row, col):
        """
        讀取導(dǎo)出文件的數(shù)據(jù)
        Returns:excel單元格數(shù)據(jù)
        """
        wb = xlrd.open_workbook(self.filename)
        sheet_name = wb.sheet_names()[0]
        sheet1 = wb.sheet_by_index(0)
        cellInfo = sheet1.cell_value(row, col)  # 獲取文件中某單元格的值
        return cellInfo  # 返回文件單元格數(shù)據(jù)
以上是一個寫入和讀取導(dǎo)出excel的封裝方法
值得注意的是,我用的是python內(nèi)置庫xlrd讀寫excel文件,xls格式文件xlrd可以讀寫,且xlrd使用1.幾的版本,最新版本不支持xls文件,openpyxl庫只支持xlsx格式文件

還有一種方法,使用pandas庫也可以讀取Excel文件
 
                