Python读取Excel

1、python先安装xlrd模块,打开命令行,输入pip install xlrd

2、python读取excel文件的步骤:1. 打开excel工作簿workbook,2. 定位到工作表sheet,3. 定位行和列,读取数据;

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)
# 根据sheet索引或者名称获取sheet内容
sheet2 = workbook.sheet_by_name(sheet2_name)
# sheet的名称,行数,列数
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)
# 获取单元格内容的数据类型
print (sheet2.cell(0,0).ctype)
if name == 'main':
read_excel()

附 获取pcharm文件路径:
1、选中项目中要读取的excel文件,右键copy path,


image.png

2、再选absulute path


image.png

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数据驱动之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'])

你可能感兴趣的:(Python读取Excel)