设为首页 加入收藏

TOP

Python操作Excel(openpyxl)
2023-07-25 21:28:57 】 浏览:43
Tags:Python 操作 Excel openpyxl

1.引入openpyxl库

安装openpyxl库:pip install openpyxl

引入openpyxl库:from openpyxl import load_worbook

2.代码实现

from openpyxl import load_workbook
#打开Excel
wb = load_workbook("C:\\Users\\Administrator\\Desktop\\testdemo.xlsx")
#定位表单
sheet = wb["s1"]
#定位单元格 行列值
print("获取最大行数:",sheet.max_row)
print("获取最大列数:",sheet.max_column)
# #遍历
test_list = []#列表
for a in range(2,sheet.max_row+1):
    test_dic = {}  # 字典
    for b in range(1,sheet.max_column+1):
        #获取指定单元格的值:sheet.cell(行,列).value
        #将获取到的数据添加到字典
        test_dic["method"]=sheet.cell(a,1).value
        test_dic["url"]=sheet.cell(a,2).value
        test_dic["data"]=eva l(sheet.cell(a,3).value)#eavl() 把数据类转换成 原本数据类型
        test_dic["expect"]=sheet.cell(a,4).value
    test_list.append(test_dic)#将字典添加到列表

print(test_list)
输出:
最大行数: 3
最大列数: 4
[{'method': 'get', 'url': 'http://www.qabujiaban.com/user/login', 'data': {'username': 'uuuu222都44', 'password': 'WJHasb124*1'}, 'expect': '0000'}, {'method': 'get', 'url': 'http://www.qabujiaban.com/user/login', 'data': {'username': 'uuuu222都44', 'password': 'WJHasb124*1'}, 'expect': '0000'}]

3.代码封装

testdemo.xlsx

 

 

 代码

#引入仓库
from openpyxl import load_workbook

class DoExcel():
    def __init__(self,file,sheet):
        self.file=file
        self.sheet=sheet

    def return_excel_value(self):
        wb = load_workbook(self.file)#打开excel
        sheet_content = wb[self.sheet]#定位sheet工作博
        data_list = []#列表用于存储测试数据
        for n in range(2,sheet_content.max_row+1):#行,第一行是标题,所以从第二行开始
            data_dict = {}#字典用于存储每组测试数据
            for m in range(2,sheet_content.max_column+1):
                data_dict["method"]=sheet_content.cell(n,2).value
                data_dict["url"] = sheet_content.cell(n, 3).value
                data_dict["data"] = eva l(sheet_content.cell(n, 4).value)#eva l()将数据类型还原
                data_dict["expect"] = sheet_content.cell(n, 5).value
            data_list.append(data_dict)#将字典存储到list
        return data_list

if __name__ == '__main__':
    data_list = DoExcel("C:\\Users\\Administrator\\Desktop\\testdemo.xlsx","s1").return_excel_value()
    print(data_list)
执行结果
[{'method': 'post', 'url': 'http://www.qabujiaban.com/user/login', 'data': {'username': 'uuuu222都44', 'password': 'WJHasb124*1'}, 'expect': '0000'}, {'method': 'get', 'url': 'http://www.qabujiaban.com/user/login', 'data': {'username': 'uuuu222都44', 'password': 'WJHasb124*1'}, 'expect': '0000'}]
Process finished with exit code 0
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇AI修复照片 下一篇用Python写一个一次性计算出加减..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目