日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

用python實現讀取xlsx表格操作_python

作者:繁星流動?>_< ? 更新時間: 2022-04-10 編程語言

前言

快要過年了,現在是工作的事情也不想干,學習也完全學不進去,關于xlsx的操作原本昨天已經寫好了,不過悲催的是,忘記發布了直接關瀏覽器關閉后發現已經丟失了。
以下操作均對照改表格操作:

在這里插入圖片描述

讀操作

獲取sheet的方法
通過索引獲取sheet表格:

table = worbook.sheets()[0]
table = worbook.sheet_by_index(0)

通過sheet名稱獲取:

table = worbook.sheet_by_name(sheet_name='case')

獲取xlsx中所有sheet:

table = worbook.sheet_names()
print(table)
打?。篶ase

獲取行和列
獲取sheet中有效行數:

row = table.nrows
print(row)
打印:8

獲取sheet中有效列數:

col = table.ncols
print(col)
打印:10

獲取一行中有多少列數據:

col = table.row_len(0)
print(col)

獲取指定行中的所有數據:

'''
rowx表示是獲取第幾行的數據
start_col表示從索引為多少開始,end_colx表示從索引為多少結束
end_colx為None表示結束沒有限制
獲取指定行中的數據并以列表的形式返回
'''
table_list = table.row_values(rowx=0, start_colx=0, end_colx=None)
print(table_list)
打?。篬'run', 'headers', 'pre_case_id', 'pre_fields', 'request_body', 'expect_result', 'assert_type', 'pass', 'update_time', 'response']

獲取列中的數據:

'''
colx表示是獲取第幾列的數據
start_rowx表示從索引為多少開始,end_rowx表示索引為多少結束
end_rowx為None表示結束沒有限制
獲取指定列中的數據并以列表的形式返回
'''
table_list = table.col_values(colx=0, start_rowx=0, end_rowx=None)
print(table_list)
打?。篬'run', 'yes', 'no', 'yes', 'no', 'no', 'no', 'no']

獲取單元格中值
獲取指定單元格中的值:

table = worbook.sheet_by_name(sheet_name='case')
value = table.cell_value(rowx=0, colx=1)
print(value)
打?。篽eaders

下面寫個例子吧,就是將所有run為yes的行打印出來,其實在日常工作中就是將run為yes的用例執行一遍啦,雖然我們并不用excel來存儲測試用例。這里直接將其定義成一個裝飾器吧。

import xlrd
class Readxlrd():

    def __init__(self,func):
        self.func = func

    def __call__(self, *args, **kwargs):
        self.func(*args)
        worbook = xlrd.open_workbook(filename=args[0])
        table = worbook.sheet_by_name(sheet_name=args[1])
        row = table.nrows
        for i in range(row):
            if i >= 1:
                combined_dict = {}
                table_list = table.row_values(rowx=i, start_colx=0, end_colx=None)
                table_head = table.row_values(rowx=0, start_colx=0, end_colx=None)
                for k, v in zip(table_head, table_list):
                    combined_dict[k] = v
                if combined_dict['run'] == 'yes':
                    print(combined_dict)


@Readxlrd
def test(route,sheet):
    print('輸入的路徑為{},輸入的sheet是{}'.format(route,sheet))
打?。狠斎氲穆窂綖镃:\Users\86182\Desktop\case.xlsx,輸入的sheet是case
{'run': 'yes', 'headers': '{"Content-Type": "application/x-www-form-urlencoded"}', 'pre_case_id': -1.0, 'pre_fields': '[]', 'request_body': '{"phone": "18262966312", "pwd": "123456"}', 'expect_result': '0', 'assert_type': 'code', 'pass': 'True', 'update_time': 44447.6884722222, 'response': ''}
{'run': 'yes', 'headers': '{"token":"token"}', 'pre_case_id': 1.0, 'pre_fields': '[{"field":"token","scope":"header"}]', 'request_body': '{}', 'expect_result': '0', 'assert_type': 'code', 'pass': 'True', 'update_time': 44447.6892476852, 'response': ''}

總結

原文鏈接:https://blog.csdn.net/HUJIANLAILE/article/details/122718747

欄目分類
最近更新