溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python處理Excel數(shù)據(jù)的方法

發(fā)布時(shí)間:2020-06-24 11:27:40 來源:億速云 閱讀:229 作者:清晨 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)Python處理Excel數(shù)據(jù)的方法,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

 

一、pandas的安裝:

  1.安裝pandas其實(shí)是非常簡單的,pandas依賴處理Excel的xlrd模塊,所以我們需要提前安裝這個(gè),安裝命令是:pip install xlrd

  2.開始安裝pandas,安裝命令是:pip install pandas

二、讀取excel文件

webservice_testcase.xlsx結(jié)構(gòu)如下:

Python處理Excel數(shù)據(jù)的方法

1.首先我們應(yīng)該先將這個(gè)模塊導(dǎo)入

import pandas as pd

2.讀取表單中的數(shù)據(jù):

sheet=pd.read_excel('test_data\\webservice_testcase.xlsx')#這個(gè)會直接默認(rèn)讀取到這個(gè)Excel的第一個(gè)表單
data=sheet.head()#默認(rèn)讀取前5行數(shù)據(jù)
print("獲取到所有的值:\n{0}".format(data))#格式化輸出   

3.也可以通過指定表單名來讀取數(shù)據(jù)

sheet=pd.read_excel('test_data\\webservice_testcase.xlsx',sheet_name='userRegister')
data=sheet.head()#默認(rèn)讀取前5行數(shù)據(jù)
print("獲取到所有的值:\n{0}".format(data))#格式化輸出

4.通過表單索引來指定要訪問的表單,0表示第一個(gè)表單,也可以采用表單名和索引的雙重方式來定位表單,也可以同時(shí)定位多個(gè)表單,方式都羅列如下所示

sheet=pd.read_excel('test_data\\webservice_testcase.xlsx',sheet_name=['sendMCode','userRegister'])#可以通過表單名同時(shí)指定多個(gè)
# sheet=pd.read_excel('test_data\\webservice_testcase.xlsx',sheet_name=0)#可以通過表單索引來指定讀取的表單
# sheet=pd.read_excel('test_data\\webservice_testcase.xlsx',sheet_name=['sendMCode',1])#可以混合的方式來指定
# sheet=pd.read_excel('test_data\\webservice_testcase.xlsx',sheet_name=[1,2])#可以通過索引 同時(shí)指定多個(gè)
data=sheet.values#獲取所有的數(shù)據(jù),注意這里不能用head()方法
print("獲取到所有的值:\n{0}".format(data))#格式化輸出

二、操作Excel中的行列

1.讀取制定的某一行數(shù)據(jù):

sheet=pd.read_excel('webservice_testcase.xlsx')#這個(gè)會直接默認(rèn)讀取到這個(gè)Excel的第一個(gè)表單
data=sheet.ix[0].values#0表示第一行 這里讀取數(shù)據(jù)并不包含表頭
print("讀取指定行的數(shù)據(jù):\n{0}".format(data))

得到了如下結(jié)果:

Python處理Excel數(shù)據(jù)的方法

2.讀取指定的多行:

sheet=pd.read_excel('test_data\\webservice_testcase.xlsx')#這個(gè)會直接默認(rèn)讀取到這個(gè)Excel的第一個(gè)表單
data=sheet.ix[[0,1]].values#0表示第一行 這里讀取數(shù)據(jù)并不包含表頭
print("讀取指定行的數(shù)據(jù):\n{0}".format(data))

得到了如下的結(jié)果:

Python處理Excel數(shù)據(jù)的方法

3.讀取指定行列的數(shù)據(jù):

sheet=pd.read_excel('test_data\\webservice_testcase.xlsx')#這個(gè)會直接默認(rèn)讀取到這個(gè)Excel的第一個(gè)表單
data=sheet.ix[0,1]#讀取第一行第二列的值
print("讀取指定行的數(shù)據(jù):\n{0}".format(data))

得到了如下結(jié)果:

Python處理Excel數(shù)據(jù)的方法

4.讀取指定的多行多列的值:

sheet=pd.read_excel('test_data\\webservice_testcase.xlsx')
data=sheet.ix[[1,2],['method','description']].values#讀取第二行第三行的method以及description列的值,這里需要嵌套列表
print("讀取指定行的數(shù)據(jù):\n{0}".format(data))

得到了如下的結(jié)果:

Python處理Excel數(shù)據(jù)的方法

 5.讀取所有行指定的列的值:

sheet=pd.read_excel('test_data\\webservice_testcase.xlsx')
data=sheet.ix[:,['method','description']].values#讀取第二行第三行的method以及description列的值,這里需要嵌套列表
print("讀取指定行的數(shù)據(jù):\n{0}".format(data))

得到了如下的結(jié)果:

Python處理Excel數(shù)據(jù)的方法

6.獲取行號輸出:

sheet=pd.read_excel('test_data\\webservice_testcase.xlsx')
print("輸出行號列表",sheet.index.values)

得到了如下的結(jié)果:

Python處理Excel數(shù)據(jù)的方法

7.獲取列名輸出:

sheet=pd.read_excel('test_data\\webservice_testcase.xlsx')
print("輸出列標(biāo)題",sheet.columns.values)

得到了如下的結(jié)果:

Python處理Excel數(shù)據(jù)的方法

8.獲取指定行數(shù)的值:

sheet=pd.read_excel('test_data\\webservice_testcase.xlsx')
print("輸出值",sheet.sample(2).values)

9.獲取指定列的值

sheet=pd.read_excel('test_data\\webservice_testcase.xlsx')
print("輸出值",sheet['description'].values)

得到了如下的結(jié)果:

Python處理Excel數(shù)據(jù)的方法

三、將excel中的每一條數(shù)據(jù)處理成字典,然后讓如一個(gè)列表中

test_data=[]
sheet = pd.read_excel(self.file_name, sheet_name=key)
for i in sheet.index.values:#獲取行號的索引,并對其進(jìn)行遍歷:#根據(jù)i來獲取每一行指定的數(shù)據(jù) 并利用to_dict轉(zhuǎn)成字典
  row_data=sheet.ix[i,['id','method','description','url','param','ExpectedResult']].to_dict()
  test_data.append(row_data)

另外,我們可以把測試用例相關(guān)的東西寫入一個(gè)配置文件當(dāng)中,讀取的時(shí)候可以根據(jù)配置文件中的內(nèi)容來進(jìn)行讀取:

配置文件如下:

[CASECONFIG]
sheet_list={'sendMCode':'all',
             'userRegister':'all',
             'verifyUserAuth':'all',
             'bindBankCard':[]
             } 

配置文件處理.py代碼如下:

import configparser
class ReadConfig:
    def read_config(self,file_path,section,option):
        cf=configparser.ConfigParser()
        cf.read(file_path,encoding="utf-8")
        value=cf.get(section,option)
        return value

project_path.py代碼如下:

import os
Project_path=os.path.split(os.path.split(os.path.realpath(__file__))[0])[0]
#配置文件路徑
case_config_path=os.path.join(Project_path,'config','case.config')
#測試用例的路徑
test_cases_path=os.path.join(Project_path,'test_data','webservice_testcase.xlsx')

然后我們把讀取excel中的內(nèi)容封裝成一個(gè)類,代碼示例如下:

from common import project_pathfrom common.read_config import ReadConfig as RC
import  pandas  as pd

class DoExcel:
    def __init__(self,file_name):
        self.file_name=file_name
        self.sheet_list=eval(RC().read_config(project_path.case_config_path,'CASECONFIG','sheet_list'))
    def do_excel(self):
        test_data=[]
        for key in self.sheet_list:
            if self.sheet_list[key] == 'all':  # 讀取所有的用例
                sheet = pd.read_excel(self.file_name, sheet_name=key)
                for i in sheet.index.values:#獲取行號的索引,并對其進(jìn)行遍歷:
                    #根據(jù)i來獲取每一行指定的數(shù)據(jù) 并利用to_dict轉(zhuǎn)成字典
                    row_data=sheet.ix[i,['id','method','description','url','param','ExpectedResult']].to_dict()
                    test_data.append(row_data)
       else:
                sheet = pd.read_excel(self.file_name, sheet_name=key)
                for i in self.sheet_list[key]:#根據(jù)list中的標(biāo)號去讀取excel指定的用例
                    row_data=sheet.ix[i-1,['id','method','description','url','param','ExpectedResult']].to_dict()
                    test_data.append(row_data)
        return  test_data
if __name__ == '__main__':
    test_data=DoExcel(project_path.test_cases_path).do_excel()
    print(test_data)

 如果將配置改成如下內(nèi)容:

[CASECONFIG]
sheet_list={'sendMCode':[1,3,5],
      'userRegister':[],
      'verifyUserAuth':[],             
      'bindBankCard':[]
           } 

我們將會得到如下的運(yùn)行結(jié)果:

[{: 1, : , : , : , : , : }, 
{: 3, : , : , : , : , : }, 
{: 5, : , : , : , : , : }]

   到此,將excel中的用例數(shù)據(jù)讀取成為[{key1:value1},{key2:value2},...,{keyn:valuen}]這樣的形式已經(jīng)完畢,但是還有很多東西需要完善,比如用例中完成參數(shù)的替換,測試完成后回寫測試數(shù)據(jù)到excel對應(yīng)的表格中等等內(nèi)容。



關(guān)于Python處理Excel數(shù)據(jù)的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI