如果 openpyxl (ws) 中的单元格包含字符串的特定部分 return 作为输出

if cell in openpyxl (ws) contains a certain section of string return as output

我被一些相对简单的问题困住了,似乎无法弄清楚..

我有一个输入,其中我输入了我要查找的字符串的部分名称的一半

        # Look for IDC S/N column
        counter = 0
        for col in df.columns:
            if col == 'IDC S/N':
                break
            else:
                counter += 1
        idc_column = counter

        # Will allow conversion of letters to number(s)
        characters = 'abcdefghijklmnopqrstuvwxyz'

        # Converted numbers to letters - 1 = A , 2 = B
        header = characters[idc_column]
       
        counter = 0 
        for x in ws[header]:
            if x.str.lower().str.contains(num.lower()):
                logger.info(x)
            else:
                print(x)

输出:

    if x.str.lower().str.contains(num.lower()):
AttributeError: 'Cell' object has no attribute 'str'

例如,如果 num 输入是 70,我希望它遍历所有 IDC S/N 列并打印包含此内容的所有内容

所以 70 的输出应该是 -

这是我想要实现的完美示例,但在 pandas

df = df.loc[df['IDC S/N'].str.lower().str.contains(num.lower(), na=False)]

仅使用 openpyxl:

from openpyxl import load_workbook

wb = load_workbook(r'spreadsheet.xlsx')
ws = wb.active

num = '70'

# Look for IDC S/N column
for cell in ws[1]:
    if cell.value == 'IDC S/N':
        idc_column = cell.column_letter
        break

# Iterate over each cell in the IDC S/N column
for cell in ws[idc_column]:
    value = cell.value
    
    # Make sure the value is a string before using the "in" operator.
    # It could be int, float, NoneType, datetime
    if isinstance(value, str):
        if num in value:
            print(f'{num} found in cell {cell.coordinate}: {value}')

用我的小测试电子表格输出: 70 found in cell B5: S508G070U

您可以从cellcolumn_letter属性中获取列字母,因此您无需手动将索引转换为字母。同样值得注意的是 openpyxl 有一个函数 get_column_letter 可以将列索引转换为列字母,以防你只有一个索引。