【使用xlrd、xlutils读写excel】

使用xlrd、xlutils读写excel

    • 1、环境和版本
    • 2、相关使用方法封装
      • [2.1 根据行下标返回对应行数据](#2.1 根据行下标返回对应行数据)
      • [2.2 根据列下标返回对应列数据](#2.2 根据列下标返回对应列数据)
      • [2.3 读取指定单元格数据](#2.3 读取指定单元格数据)
      • [2.4 通过表单名读取全部数据](#2.4 通过表单名读取全部数据)
      • [2.5 通过表索引读取全部数据](#2.5 通过表索引读取全部数据)
      • [2.6 向已存在sheet中追加数据](#2.6 向已存在sheet中追加数据)
      • [2.7 原文件基础上新建的sheet并写入数据](#2.7 原文件基础上新建的sheet并写入数据)
    • 3、其他踩坑

1、环境和版本

  • 电脑:win
  • excel文件格式.xls
  • xlrd 版本 1.2.0(高版本存在部分属性不兼容),安装指定版本pip install xlrd == 1.2.0
  • xlutils 版本:2.0.0

2、相关使用方法封装

2.1 根据行下标返回对应行数据

python 复制代码
def read_excel_by_row(file_path, sheet_index, row_index):
    """读取指定行数据"""
    data = xlrd.open_workbook(file_path)
    sheet = data.sheet_by_index(sheet_index)
    nrows = sheet.nrows  # 行数
    ncols = sheet.ncols  # 列数
    try:
        table_list = sheet.row_values(rowx=row_index, start_colx=0, end_colx=None)  # start_colx:开始列,end_colx:结束列
        return table_list
    except Exception as e:
        print("当前表单行数%s行%s列" % (nrows, ncols), e)

2.2 根据列下标返回对应列数据

python 复制代码
def read_excel_by_col(file_path, sheet_index, col_index):
    """读取指定列数据"""
    data = xlrd.open_workbook(file_path)
    sheet = data.sheet_by_index(sheet_index)
    nrows = sheet.nrows  # 行数
    ncols = sheet.ncols  # 列数
    try:
        table_list = sheet.col_values(colx=col_index, start_rowx=0, end_rowx=None)  # start_rowx:开始行,end_colx:结束行
        return table_list
    except Exception as e:
        print("当前表单行数%s行%s列" % (nrows, ncols), e)

2.3 读取指定单元格数据

python 复制代码
def read_excel_by_cell(file_path, sheet_index,row_index,col_index):
    """
    读取指定单元格数据
    :param file_path: 文件路径. .xls格式的文件
    :param sheet_index: sheet表索引
    :param row_index: 行下标
    :param col_index: 列下标
    :return: 第row_index行col_index数据
    """
    wb = xlrd.open_workbook(file_path)
    sheet = wb.sheet_by_index(sheet_index)
    value = sheet.cell_value(row_index, col_index)
    # value_type = sheet.cell_type(row_index, col_index) # 单元格类型  0->empty,1->string,2->number,3->date,4->boolean,5->error
    return value

2.4 通过表单名读取全部数据

python 复制代码
def red_excel_by_sheet_name(file_path, sheet_name):
    """
    读取excel数据并返回
    :param file_path: 文件路径 .xls文件
    :param sheet_index: sheet表单所以
    :return: 表单List
    """
    data = xlrd.open_workbook(file_path)
    # table = data.sheet_by_index(sheet_index)
    table = data.sheet_by_name(sheet_name)
    # 表格行数
    nrows = table.nrows #行数
    ncols = table.ncols
    # print(nrows, ncols)
    table_list = []
    for row_index in range(0, nrows):
        temp_list = table.row_values(rowx=row_index, start_colx=0, end_colx=None)  # start_colx:开始列,end_colx:结束列
        table_list.append(temp_list)
    return table_list

2.5 通过表索引读取全部数据

python 复制代码
def red_excel_by_sheet_index(file_path, sheet_index):
    """
    通过表单索引读取excel数据并返回
    :param file_path: 文件路径
    :param sheet_index: 表单索引
    :return:对应表单的数据
    """
    data = xlrd.open_workbook(file_path)
    table = data.sheet_by_index(sheet_index)
    # table = data.sheet_by_name(sheet_index)
    # 表格行数
    nrows = table.nrows
    ncols = table.ncols
    # print(nrows, ncols)
    table_list = []
    for row_index in range(0, nrows):
        temp_list = table.row_values(rowx=row_index, start_colx=0, end_colx=None)  # start_colx:开始列,end_colx:结束列
        table_list.append(temp_list)
    return table_list

2.6 向已存在sheet中追加数据

python 复制代码
def append_to_sheet(file_path, sheet_tag, data):
    """向已存在的表中追加数据
    :param file_path: 文件路径(sheet已经存在的情况)
    :param sheet_tag: sheet表标识 sheet_name or sheet_index
    :param data: 要追加的数据
    :return: None
    """
    try:
        # 打开文件
        openFile = xlrd.open_workbook(file_path)
        # 读取文件,准备写入信息
        if isinstance(sheet_tag, int): #如果参数是int根据索引查找表单
            max_row = openFile.sheet_by_index(sheet_tag).nrows
        else: #如果参数是str根据名称查找表单
            max_row = openFile.sheet_by_name(sheet_tag).nrows
        print("当前最大行=", max_row)
        write = copy(openFile)
        write_sheet = write.get_sheet(sheet_tag)
        start_row = max_row  # 从表格的第5行开始写入数据
        # 一行一行的写,一行对应的所有列
        for d in data:  # 控制行
            col = 0
            for value in d:  # 控制每一列
                write_sheet.write(start_row, col, value)  # rou代表列,col代表行,value写入值
                col += 1
            start_row += 1
        # 保存
        write.save(file_path)
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到。")
    except xlrd.XLRDError:
        print("无法读取Excel文件,请检查文件格式或内容。")
    except Exception as e:
        print(f"发生未知错误:{e}")

2.7 原文件基础上新建的sheet并写入数据

python 复制代码
def append_date_to_new_sheet(file_path, sheet_name,data):
    """
    原文件基础上新建的sheet并写入数据
    :param file_path:
    :param sheet_name:
    :param data:list数据,例:data = [[1,2],[3,4]]
    :return:None
    """
    openFile = xlrd.open_workbook(file_path)
    write = copy(openFile)
    write.add_sheet(sheet_name)
    write_sheet = write.get_sheet(sheet_name) # 已存在的表单,实际需要新建
    row = 0  # 从表格的第二行开始写入数据
    # 一行一行的写,一行对应的所有列
    for d in data:  # 控制行
        col = 0
        for one in d:  # 控制每一列
            write_sheet.write(row, col, one)  # rou代表列,col代表行,one写入值
            col += 1
        row += 1
    write.save(file_path)

3、其他踩坑

xlrd 仅1.2.0 版本支持.xls 文件,更高版本不支持,没有删除sheet功能

openpyxl 支持.xlsx 读取的时候一直显示文件被损坏, 不支持.xls格式,有remove功能,但是使用过程中也有问题,后续研究明白再做补充吧

相关推荐
XYX的Blog11 小时前
Pandas基础07(Csv/Excel/Mysql数据的存储与读取)
mysql·excel·pandas
东京老树根15 小时前
Excel 技巧23 - 在Excel中用切片器做出查询效果(★★★)
笔记·学习·excel
东京老树根2 天前
Excel 技巧22 - Ctrl+D 向下复制(★★),复制同间距图形
笔记·学习·excel
如意机反光镜裸2 天前
如何批量导入竖版Excel表到数据库
数据库·excel
NiNg_1_2342 天前
FastExcel使用详解
开发语言·excel·fastexcel
小奥超人4 天前
EXCEL教程:如何打开Excel隐藏部分?
windows·经验分享·microsoft·excel·办公技巧
Eiceblue4 天前
C# 添加、替换、提取、或删除Excel中的图片
开发语言·c#·excel·visual studio
ynrainy4 天前
Excel分区间统计分析(等步长、不等步长、多维度)
excel
扎量丙不要犟5 天前
excel如何查找一个表的数据在另外一个表是否存在
rust·excel
xun-ming5 天前
Excel中LOOKUP函数的使用
excel·xlookup·vlookup·lookup·hlookup