Python / Openpyxl - 在列中查找字符串并返回行号

时间:2018-05-23 15:08:50

标签: python row openpyxl

我是一个相当新的Python用户,我有一个excel表,其中包含多个未格式化的表。我试图用Python和openpyxl迭代B列,以便找到相应表的标题。当我找到标题时,我想将行号保存在变量中。不幸的是,代码没有按预期运行,我没有收到任何错误消息。您可以在下面找到示例excel表的截图以及我的代码。谢谢你的帮助!

start = 1
end = 14
sheet = wb[('Positioning')]

for col in sheet.iter_cols(min_col=2,max_col=2, min_row = start, max_row=end):
    for cell in col:
        if cell.value == 'Table 1':
            table1 = cell.row
        elif cell.value == 'Table 2':
            table2 = cell.row

Screenshot - Excel Example

2 个答案:

答案 0 :(得分:0)

这可以通过多种方式完成,这是一种方式: 假设'Table'不会出现在表中的任何地方,而是显示在表中的标题。

from openpyxl import Workbook
from openpyxl import load_workbook,styles

wb = load_workbook('Test.xlsx') #Load the workbook
ws = wb['Sheet1'] #Load the worksheet

#ws['B'] will return all cells on the B column until the last one (similar to max_row but it's only for the B column)
for cell in ws['B']:
    if(cell.value is not None): #We need to check that the cell is not empty.
        if 'Table' in cell.value: #Check if the value of the cell contains the text 'Table'
            print('Found header with name: {} at row: {} and column: {}. In cell {}'.format(cell.value,cell.row,cell.column,cell))

打印哪些:

Found header with name: Table 1 at row: 2 and column: B. In cell <Cell 'Sheet1'.B2>
Found header with name: Table 2 at row: 10 and column: B. In cell <Cell 'Sheet1'.B10>

答案 1 :(得分:0)

以下是在列或行中搜索字符串的方法。您可以使用column固有的术语col_idxopenpyxl分别表示字母和Excel工作表的编号。

wb = load_workbook()
ws = wb.active

col_idx, row = search_value_in_col_index(ws, "_my_search_string_")

def search_value_in_column(ws, search_string, column="A"):
    for row in range(1, ws.max_row + 1):
        coordinate = "{}{}".format(column, row)
        if ws[coordinate].value == search_string:
            return column, row
    return column, None


def search_value_in_col_idx(ws, search_string, col_idx=1):
    for row in range(1, ws.max_row + 1):
        if ws[row][col_idx].value == search_string:
            return col_idx, row
    return col_idx, None


def search_value_in_row_index(ws, search_string, row=1):
    for cell in ws[row]:
        if cell.value == search_string:
            return cell.column, row
    return None, row