Python之openpyxl操作excel

安装:

pip install openpyxl

 

读取:

一行行读取

from openpyxl import load_workbook

# 读取excel方法
def read_excel():

    path = r"D:\Users\72036454\Desktop\python_automation\URL\Testcase_excel\test.xlsx"  # 指定excel文件路径
    excel = load_workbook(path)  # 读取excel


    sheet = excel.active  # 返回当前操作sheet页
    sheet = excel._sheets  # 返回所有sheet页
    sheet = excel['Sheet1']  # 通过名称读取指定sheet页
    sheet = excel._sheets[0]  # 通过下标读取指定sheet页

    for i in sheet.values:  # 一行行遍历sheet页内的值
        print(i)

read_excel()

 

读取指定列

from openpyxl import load_workbook

# 读取excel文件
excel = load_workbook('excel文件路径')
# 读取sheet页
sheet = excel['sheet页名']

# 方法一,只取某一列
# 遍历全部列表,只读取"A"列
for row in sheet.iter_rows():
    for cell in row:
        if 'A' in cell.coordinate:
            # 打印格式:行号  数据
            print(cell.coordinate, cell.value)


# 方法二: 通过范围区间读取多个列
prj = sheet.columns
prjtuple = tuple(prj)
for idx in range(0, 4):  # 遍历A、B、C、D列 。如果其中一列都没有数据,则会报错,只要有一个数据就不会报错, 无数据行显示为None
    for cell in prjtuple[idx]:
        # 打印格式:行号  数据
        print(cell.coordinate, cell.value)

 

读取某个单元格

from openpyxl import load_workbook

# 打开excel文件
excel = load_workbook(r'./TestExampleFile/test.xlsx')

# 读取sheet页
sheet = excel['Sheet1']

# 读取第3行,第5列单元格的数据
ce = sheet.cell(3,5)

# 打印单元格内的数据
print(ce.value)

 

读取excel值的同时输出它的所在行和列

import openpyxl

excel = openpyxl.load_workbook(r'test_case_data.xlsx')
sheet = excel['Sheet1']

# 遍历sheet对象
for row in sheet:
    # 遍历每个单元格
    for cell in row:
        # 同时打印读取到单元格的值、行数、列数
        print(cell.value, cell.row, cell.column)

 

 写入:

from openpyxl import load_workbook

# 打开excel文件
wb = load_workbook(r'./TestExampleFile/test.xlsx')
# 读取sheet页
sheet = wb.active
# 将数据写入第4行,第5列的表格中
sheet.cell(row=4, column=5).value = "hello"
# 保存excel
wb.save(r'./TestExampleFile/test.xlsx')
# 结束
print("运行结束!")
# 注意:写入时excel文件必须是关闭状态,否则会报错

 

编辑:

import openpyxl

# 打开需要编辑的文件
wb = openpyxl.load_workbook(r"C:\Users\86158\Desktop\pythonProject2\data\ual_data.xlsx") #打开文件

# 打开需要编辑的sheet页名称
sheet = wb["sheet1"]  # 读取sheet页

# 需要编辑的行column、列roe,以及编辑写入的内容value
sheet.cell(column=10, row=2, value="你好")

# 输入后保存文件
wb.save(r"C:\Users\86158\Desktop\pythonProject2\data\ual_data.xlsx")

 

新增:

后续更新.....

相关操作

创建一个工作薄:wb = openpyxl.Workbook()
新增一个sheet表单:wb.create_sheet('test_case')
保存case.xlsx文件:wb.save('cases.xlsx')
打开工作簿:wb = openpyxl.load_workbook('cases.xlsx')
选取表单:sh = wb['Sheet1'
读取第一行、第一列的数据:ce = sh.cell(row = 1,column = 1)
按行读取数据:row_data = list(sh.rows)
关闭工作薄:wb.close()
按列读取数据:columns_data = list(sh.columns)
写入数据之前,该文件一定要处于关闭状态
写入第一行、第四列的数据 value = 'result':sh.cell(row = 1,column = 4,value = 'result')
获取最大行总数、最大列总数:sh.max_row、sh.max_column
del 删除表单的用法:del wb['sheet_name'] 
remove 删除表单的用法:sh = wb['sheet_name'] wb.remove(sh) 

 

posted @ 2022-04-25 20:26  博无止境  阅读(643)  评论(0编辑  收藏  举报