【问题标题】:Python / Openpyxl - Find Strings in column and return row numberPython / Openpyxl - 在列中查找字符串并返回行号
【发布时间】:2018-05-23 15:08:50
【问题描述】:

我是一个相当新的 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

【问题讨论】:

  • 标题是否总是被命名为'Table 1'、'Table 2'等(增量)?

标签: python row openpyxl


【解决方案1】:

以下是在列或行中搜索字符串的方法。您可以使用columncol_idx,它们是openpyxl 固有的术语,分别表示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

【讨论】:

    【解决方案2】:

    这可以通过多种方式完成,这是一种方式: 假设“表格”除了所述表格的标题外不会出现在表格中的任何地方。

    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>
    

    【讨论】:

    • 如何不对列“B”进行硬编码,而是循环遍历找到字符串匹配的当前列?
    猜你喜欢
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多