在电子表格中查找变量字符串的地址

问题描述 投票:2回答:1

我有一个Google电子表格,第1列包含test_name,第二列包含测试结果(通过或失败)。我想在电子表格中搜索test_name(字符串),如果匹配,则获取字符串的行,列并在column2中更新结果。

try:
    worksheet = sh.worksheet(sheetName)
    print("got access to worksheet",worksheet)
except Exception as Ex: 
    print(Ex)

with open(PATH) as f:
    for line in f:
        if line.startswith("PASS") or line.startswith("FAIL") or line.startswith("SKIP") or line.startswith('INELIGIBLE') or line.startswith('ERROR'):
            print("line",line)
            index=line.index("")
            result=line[0:index]
            tname=line[index+1:]
            print("result",result)
            print(result+" "+ tname)
            list1.append(tname)
            print("*******************************")
            try:
                cell=sh.find(tname)
                row=cell.row
                column=cell.col
                print("row",row)
                print("col",col)
                print("cell",cell)
            except Exception as Ex:
                print(Ex)

cell.find(tname)显示错误,无法获取不区分大小写(或间隔)的字符串:

'Spreadsheet'对象没有属性'cell'

我已经获取了字符串的确切行col。

python-3.x google-sheets gspread
1个回答
0
投票

你可以尝试下面的代码:

from openpyxl import load_workbook

wb = load_workbook('~/Documents/test_sheet.xlsx')
sheet = wb.get_sheet_by_name('Sheet 1')
sheet = wb.active

def get_row_column_values(workbook,sheet, col1, col2, row_num_to_startwith, string_to_match):
     passed='PASS'
     failed='FAIL'

     for i in range(row_num_to_startwith, sheet.max_column+1):
     if sheet[col1+str(i)].value:

        if sheet[col1+str(i)].value.strip().lower() == str(string_to_match.lower()):
            sheet[col2+str(i)] = passed
        else:
            sheet[col2+str(i)] = failed

     workbook.save('~Documents/another_copy.xlsx')


get_row_column_values(wb, sheet, 'A', 'B', 3, 'PQR')

输出可以看作:

© www.soinside.com 2019 - 2024. All rights reserved.