openpyxl使用实例

2022-08-07 09:06:37

* coding:utf-8*

import openpyxl

class HandleExcel:
“”"
处理excel文件
“”"

def __init__(self, filename, sheetname):
    """
    初始化,定义实例属性
    :param filename:要处理的文件名称
    :param sheetname:要处理的文件sheet页名称
    """
    self.filename = filename
    self.sheetname = sheetname
    # 打开文件
    self.wb = openpyxl.load_workbook(self.filename)
    # 获取sheet页数据,可以用多种方法:
    """
    可以用多种方法:
    wb.sheetnames #获取所有的sheet(列表),返回值是一个列表
    ws = wb.sheetnames[0] #通过索引值获取sheet 0 1 2 分别对应excel 文件sheet 页1. 2.3  
    ws = wb.get_sheet_by_name('Sheet_name') 等价于  ws=wb['Sheet_name'] #获取指定的sheet:sheet_name
    """
    self.sh = self.wb[self.sheetname]
    # 获取所有行的数据
    self.datas = list(self.sh.rows)
    # 获取所有列的数据
    self.column = list(self.sh.columns)
    # 获取到的列/行数据类型为列表类型!
    print("列数据:", self.column)
    """
    列数据: 列表中的数据,是元组嵌套。一个列/行为一个元组
    [
    (<Cell 'login'.A1>, 
    <Cell 'login'.A2>, 
    <Cell 'login'.A3>, 
    <Cell 'login'.A4>, 
    <Cell 'login'.A5>, 
    <Cell 'login'.A6>, 
    <Cell 'login'.A7>), 
    (<Cell 'login'.B1>,
     <Cell 'login'.B2>,
      <Cell 'login'.B3>, 
     <Cell 'login'.B4>, 
     <Cell 'login'.B5>, 
     <Cell 'login'.B6>, 
     <Cell 'login'.B7>,
      (<Cell 'login'.C1>, 
      <Cell 'login'.C2>, 
      <Cell 'login'.C3>, 
      <Cell 'login'.C4>, 
      <Cell 'login'.C5>, 
      <Cell 'login'.C6>,
       <Cell 'login'.C7>)
    ]
    """
    # #####获取单个数据:先获取到列表元素,然后在获取元组位置,定位到具体的单元格,通过cell.value
    print("#################获取具体的值方法一:通过行、列################")
    # 定位到具体的单元格:cell
    # 定位到第一行第一列:A1
    self.cell = self.column[0][0]
    print("当前单元格的位置:", self.cell)
    # 获取单元格里面的值
    print("{}单元格的值是:{}".format(self.cell, self.cell.value))
    """
    #################获取具体的值################
    当前单元格的位置: <Cell 'login'.A1>
    <Cell 'login'.A1>单元格的值是:case_id
    """
    print("#################获取具体的值方法二:通过指定列,行################")

    print("A列,第一个单元的值 A1:", self.sh['A1'].value)
    """
    #################获取具体的值方法二:通过指定列,行################
    A列,第一个单元的值 A1: case_id
    """
    print("#########################获取列、行############################")
    print(self.sh['A'], end=" ")  # A那一列(元组)
    """
    (<Cell 'login'.A1>, <Cell 'login'.A2>, <Cell 'login'.A3>, <Cell 'login'.A4>, <Cell 'login'.A5>, <Cell 'login'.A6>, <Cell 'login'.A7>) 
    """
    print()
    print(self.sh['A:C'], end="")  # A到C列
    print()
    print(self.sh[1], end="")  # 第1行(元组)
    """
    (<Cell 'login'.A1>, <Cell 'login'.B1>, <Cell 'login'.C1>, <Cell 'login'.D1>, 
    <Cell 'login'.E1>, <Cell 'login'.F1>, <Cell 'login'.G1>, <Cell 'login'.H1>)
    """
    print()
    print(self.sh[1:3], end="")  # 第1到3行(元组)

    print("################################修改表格中的数据#########################################")
    # 给指定的单元格赋值/写入新的值
    # 方法一:直接指定相应的单元格赋值
    self.sh['I1'].value = "test"
    # 方法二:通过指定行、列。值,来修改对应的值
    self.sh.cell(row=9, column=1, value="test01")
    print(self.sh['I1'].value)
    print(self.sh.cell(row=9, column=1).value)
    self.wb.save(self.filename)
    """
    ################################修改表格中的数据#########################################
    test
    test01
    """

    print("####################合并单元格########################")
    self.sh.merge_cells(start_row=9, start_column=1, end_row=9, end_column=2)
    self.wb.save(self.filename)
    print("合并成功!")

    print('######################新增文件、复制文件############################')
    # 创建一个新的sheet页:login1,  index用来表示穿件的sheet页面放在哪个页签后面,默认在当前sheet后面,从左边到右边计数从0开始
    self.sh1 = self.wb.create_sheet("login1", index=0)  # 这里index=0 ,表示新增的sheet页放在第一个
    self.wb.save(self.filename)
    print("新增成功!")

def read_excel(self):
    # 获取用例数据
    cases_data = []
    for cases in self.datas[1:]:
        case_datas = []
        for item in cases:
            case_datas.append(item.value)
        cases_data.append(dict(case_datas))
    return cases_data

ifname == ‘main’:
excel = HandleExcel(r’./cases.xlsx’, ‘login’)
res = excel.read_excel()

  • 作者:IT求学人
  • 原文链接:https://blog.csdn.net/Mihoutaoxiaozi/article/details/111875490
    更新时间:2022-08-07 09:06:37