openpyxl
Install third-party libraries:
pip install openpyxl
Ideas:
- Open the file using the load_workbook module of openpyxl
- The sheetnames method gets all the sheets in the table
- cell(x,y) get cell data
- max_row , max_column get the maximum number of rows and columns
- Iterate through all the data in the table
- Format
[{},{},{},...,{},{},{}]
- Format
Implementation code:
from openpyxl import load_workbook
# 打开指定文件
filename = "/Users/yanghui/PycharmProjects/unittestProject/data/crm_test_data.xlsx"
wb = load_workbook(filename)
# 获取工作簿
sheet = wb.sheetnames
# 获取对应单元格数据
# sheet[0]取的值只是一个字符串(当前工作簿的一个sheet值),要想获取当前sheet的工作簿内容,需要wb[sheet[0]]
sheet_name = wb[sheet[0]]
getValue = sheet_name.cell(2,3).value
# print(getValue)
# 增加/修改数据
setValue = sheet_name.cell(2,2).value = '登陆新接口'
wb.save(filename)
# 获取工作簿的内容 --- 遍历
rows = sheet_name.max_row
cols = sheet_name.max_column
# 定义一个数组,把遍历出来的所有接口内容存到数组中;
caseData = []
# 表格下标从1开始,(2,rows)获取不到最后一行数据,所以需要加一
# 这里不理解可以实际print一下
for i in range(2,rows+1):
case = {
} # 一条接口用例一条数据
for j in range(1,cols+1):
value = sheet_name.cell(i,j).value
case[sheet_name.cell(1,j).value] = value
caseData.append(case)
print(caseData)
The above will get all the data in the specified sheet~~~