1、python先安裝xlrd模塊,打開命令行钓瞭,輸入pip install xlrd
2浊竟、python讀取excel文件的步驟:1. 打開excel工作簿workbook怨喘,2. 定位到工作表sheet,3. 定位行和列振定,讀取數(shù)據(jù)必怜;
3、讀取excel示例代碼如下:
-- coding: utf-8 --
import xlrd
def read_excel():
# 打開文件
workbook = xlrd.open_workbook(r'D:\Program Files\JetBrains\PyCharm Community Edition 2020.3.3\jbr\bin\D\pythonProject\com\mysql\001test.xls')
# 獲取所有sheet
print(workbook.sheet_names()) # [u'sheet1', u'sheet2']
#獲取sheet2
sheet2_name= workbook.sheet_names()[0]
print (sheet2_name)
# 根據(jù)sheet索引或者名稱獲取sheet內容
sheet2 = workbook.sheet_by_name(sheet2_name)
# sheet的名稱后频,行數(shù)梳庆,列數(shù)
print (sheet2.name,sheet2.nrows,sheet2.ncols)
rows = sheet2.row_values(0) # 獲取第1行內容
cols = sheet2.col_values(0) # 獲取第1列內容
print (rows)
print (cols)
#獲取單元格內容的三種方法
print (sheet2.cell(0,0).value)
print (sheet2.cell_value(0,1))
print (sheet2.row(2)[0].value)
# 獲取單元格內容的數(shù)據(jù)類型
print (sheet2.cell(0,0).ctype)
if name == 'main':
read_excel()
附 獲取pcharm文件路徑:
1、選中項目中要讀取的excel文件卑惜,右鍵copy path,
2膏执、再選absulute path
3、復制到路徑貼到如下代碼塊中
workbook = xlrd.open_workbook(r'D:\Program Files\JetBrains\PyCharm Community Edition 2020.3.3\jbr\bin\D\pythonProject\com\mysql\001test.xls')
pytest數(shù)據(jù)驅動之EXCEL
-- coding: utf-8 --
import codecs
import json
import os
import time
import pytest
from openpyxl import load_workbook
def read_data_from_excel(excel_file, sheet_name):
return_value = []
if not os.path.exists(excel_file):
raise ValueError("File not exists")
wb = load_workbook(excel_file)
for s in wb.sheetnames:
if s == sheet_name:
sheet = wb[sheet_name]
for row in sheet.rows:
return_value.append([col.value for col in row])
print(return_value)
return return_value[1:]
class TestBaidu:
# 注意残揉,此處調用我換成了讀Excel的方法
@pytest.mark.parametrize('search_string, expect_string', read_data_from_excel(r'D:\Program Files\JetBrains\PyCharm Community Edition 2020.3.3\jbr\bin\D\pythonProject\com\mysql\002.xlsx', 'Sheet1'))
def test_baidu_search(self, search_string, expect_string):
search_results = 'bbb'
print(search_string)
print(expect_string)
#assert (expect_string in search_results) is True
if name == "main":
pytest.main(['-s', '-v','tests_pytest_ddt'])