openpyxl、xlrd获取工作表中指定内容首次出现的行列号

本文介绍了使用Python库openpyxl和xlrd分别在xlsx和xls文件中实现查找指定内容所在的行号和列号的方法,适用于数据处理和文件操作场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分别对xlsx和xls文件进行区分行号和列号的返回

本文所用openpyxl、xlrd为python三方库,下载安装可直接cmd执行pip install openpyxl、pip install openpyxl。


# 获取指定内容所在单元格的行列 path:对应文件路径 sheet:对应sheet名称 character:指定内容
def get_row_xlsx(path, sheet, character):  
    import openpyxl
    wb = openpyxl.load_workbook(path)
    st = wb[sheet]
    for x in range(1, st.max_row + 1):
        for y in range(1, st.max_column + 1):
            if st.cell(x, y).value is not None:
                text = st.cell(x, y).value
                if character == str(text):
                    row = x
                    return row


def get_column_xlsx(path, sheet, character):
    import openpyxl
    wb = openpyxl.load_workbook(path)
    st = wb[sheet]
    for x in range(1, st.max_row + 1):
        for y in range(1, st.max_column + 1):
            if st.cell(x, y).value is not None:
                text = st.cell(x, y).value
                if character == str(text):
                    col = y
                    return col


def get_row_xls(path, sheet, character):
    import xlrd
    wb = xlrd.open_workbook(path)
    st = wb.sheet_by_name(sheet)
    for x in range(st.nrows):
        for y in range(st.ncols):
            if st.cell_value(x, y) is not None:
                text = st.cell_value(x, y)
                if character == str(text):
                    row = x
                    return row


def get_column_xls(path, sheet, character):
    import xlrd
    wb = xlrd.open_workbook(path)
    st = wb.sheet_by_name(sheet)
    for x in range(st.nrows):
        for y in range(st.ncols):
            if st.cell_value(x, y) is not None:
                text = st.cell_value(x, y)
                if character == str(text):
                    col = y
                    return col

原创文章,转载请注明出处,谢谢配合!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值