python 读取excel

读取指定的excel文件

文件目录结构
在这里插入图片描述

excel表格数据内容
excel文件内容
使用频率高的几个用法

# 文件readExcel.py
from openpyxl import load_workbook
workbook = load_workbook('demo.xlsx')  # 实例化一个excel文件操作对象
sheet = workbook['Sheet1']  # 指定excel表单名称Sheet1,之后操作都在Sheet1操作
row = sheet.max_row  # 最大行数
column = sheet.max_column # 最大列数
print(workbook.sheetnames) # 打印所有表单名称
print(sheet.rows) # sheet表单的行生成器
print(sheet.cell(1, 1).value) # 第一行第一列的值
print(row, column)

打印结果内容:
打印结果任务:
使用常用功能读取Sheet1表格所有内容展示结果:
[
{‘caseId’: 1, ‘caseName’: 2, ‘method’: 3, ‘data’: 4},
{‘caseId’: 2, ‘caseName’: 3, ‘method’: 4, ‘data’: 5},
{‘caseId’: 3, ‘caseName’: 4, ‘method’: 5, ‘data’: 6},
{‘caseId’: 4, ‘caseName’: 5, ‘method’: 6, ‘data’: 7},
{‘caseId’: 5, ‘caseName’: 6, ‘method’: 7, ‘data’: 8},
{‘caseId’: 6, ‘caseName’: 7, ‘method’: 8, ‘data’: 9},
{‘caseId’: 7, ‘caseName’: 8, ‘method’: 9, ‘data’: 10},
{‘caseId’: 8, ‘caseName’: 9, ‘method’: 10, ‘data’: 11},
{‘caseId’: 9, ‘caseName’: 10, ‘method’: 11, ‘data’: 12}
]
对应excel10行数据,第一行标题为字典的键、每一行对应列表的一个元素。(为之后接口自动化数据结构奠基)

# 文件readExcel.py
class ExcelTreating:
    def __init__(self, filename):
        self.workbook = load_workbook('demo.xlsx')

    def read_excel(self, sheet_name):
        test_data = []
        sheet = self.workbook[sheet_name]
        max_row = sheet.max_row
        max_column = sheet.max_column
        title = [sheet.cell(1, i+1).value for i in range(max_column)] # 将第一行的值存到title列表

        for row in range(2, max_row+1):
            col_content = [sheet.cell(row, column).value for column in range(1, max_column+1)]
            test_data.append(dict(zip(title, col_content)))
        return test_data


res = ExcelTreating('demo.xlsx').read_excel('Sheet1')
print(res)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值