繁体   English   中英

如何使用 Python 根据 Excel 中的单元格值选择动态范围

[英]How to select a dynamic range based on a cell value in Excel with Python

我很难找到与我的问题相关的任何内容。 到目前为止,我所发现的只是根据静态范围选择范围,但不幸的是,数据可能每周都在变化。

有多个不同行和列的数据块位于同一工作表中,但在数据上方具有标题。 我的目标是找到一个标题,即第 36 行或第 40 行,向下移动一行并基本上执行 ctrl+down ctrl+right 来选择一个范围,然后创建一个表格并根据标题命名一个表格。 报告示例

import openpyxl

def tables(title):
    for cell in pws_sheet["A"]: #pws_sheet["A"] will return all cells on the A column until the last one
        if (cell.value is not None): #check if cell is not empty
            if title in cell.value: #check if the value of the cell contains the title
                row_coord = cell.row #put row number into a variable

tables("All Call Distribution by Hour")

我目前能够找到基于标题的行,将标题保存到一个变量中,但是我无法弄清楚如何选择每个数据块的右下角并将其选择为一个范围并从中创建表格那个范围。

编辑 1:标题行是正确的,结束行的作用类似于max_row ,并且num_cols显示 cell.values 而不是该表的单个 max 列。

def find_table(title, sheet):
    title_row = None
    for row in sheet.iter_rows():
        if row[0].value == title:
            #Find the title row
            title_row = row[0].row
        if row[0].value is None and title_row:
            end_row = row[0].row - 1
            num_cols = [cell.value for cell in sheet[title_row+1] if cell.value is not None]
    else:
        #The last row in the sheet
        end_row = row[0].row
    print(f"Row: {title_row}, Column: {num_cols}, End Row: {end_row}")
    return title_row, num_cols, end_row

输出: Row: 40, Column: ['Within', '# Calls', '% Calls'], End Row: 138

要选择您想要的单元格,请尝试这样的操作

def find_table(sheet, title):
    title_row = None
    for row in sheet.iter_rows():
        if row[0].value == title:
            # Find the title row
            title_row = row[0].row
        if row[0].value is None and title_row:
            end_row = row[0].row - 1
            break
    else:
        # The last row in the sheet
        end_row = row[0].row
return title_row, end_row

您可以找到给定表的特定列数;

num_cols = len([cell.value for cell in sheet[title_row+1] if cell.value is not None])

这应该给你开始和结束行,以及列数。 然后,您可以选择这些单元格并使用它们以适合您的特定示例的任何形式“制作表格”。

如果要使用 Excel 的“A1”样式表示法选择一系列单元格,您始终可以使用openpyxl.utils.cell.get_column_letter(idx)将数字列号转换为相应的字母。

此解决方案非常简单,并且对 Excel 表格的格式做了一些假设,例如数据始终从 ColumnA 开始,ColumnA 中的空单元格表示完全空行,并且标题行始终跟在标题行之后. 您可能还想添加一些错误处理 - 例如,如果没有找到标题行怎么办? 希望这可以让您朝着正确的方向开始,并尝试一些想法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM