简体   繁体   English

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

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

I am having a hard time trying to find anything relating to my question.我很难找到与我的问题相关的任何内容。 All I have found so far is selecting ranges based off of a static range, but unfortunately the data can change from week to week.到目前为止,我所发现的只是根据静态范围选择范围,但不幸的是,数据可能每周都在变化。

There are multiple data blocks with different rows and columns located in the same sheet but have titles above the data.有多个不同行和列的数据块位于同一工作表中,但在数据上方具有标题。 My goal is to find a title ie row 36 or 40, move a row down and essentially do a ctrl+down ctrl+right for selecting a range and then creating a table and naming a table based off of the title.我的目标是找到一个标题,即第 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")

I'm currently able to find the row based off of the title, save the title into a variable, but I am lost on figuring out how to select the bottom right of each data block and selecting it as a range and creating the table from that range.我目前能够找到基于标题的行,将标题保存到一个变量中,但是我无法弄清楚如何选择每个数据块的右下角并将其选择为一个范围并从中创建表格那个范围。

EDIT 1: Title row is correct, end row is the acting like max_row , and the num_cols is showing the cell.values instead of just a single max column for that table.编辑 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

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

For selecting the cells you want, try something like this要选择您想要的单元格,请尝试这样的操作

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

You can find the specific number of columns, for the given table with;您可以找到给定表的特定列数;

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

That should give you the start and end rows, and the number of columns.这应该给你开始和结束行,以及列数。 You can then select those cells and use them to "make a table" in whatever form that takes for your specific example.然后,您可以选择这些单元格并使用它们以适合您的特定示例的任何形式“制作表格”。

If you want to select a range of cells using Excels 'A1' style notation, you can always use openpyxl.utils.cell.get_column_letter(idx) to translate a numeric column number into the corresponding letter.如果要使用 Excel 的“A1”样式表示法选择一系列单元格,您始终可以使用openpyxl.utils.cell.get_column_letter(idx)将数字列号转换为相应的字母。

This solution is quite simplistic, and makes some assumptions about the format of your excel sheets, such as that the data always starts in ColumnA, that an empty cell in ColumnA indicates a totally empty row, and that the heading row always follows the title row.此解决方案非常简单,并且对 Excel 表格的格式做了一些假设,例如数据始终从 ColumnA 开始,ColumnA 中的空单元格表示完全空行,并且标题行始终跟在标题行之后. You would also probably want to add some error handling - for example, what if the title row is not found?您可能还想添加一些错误处理 - 例如,如果没有找到标题行怎么办? Hopefully this can give you a start in the right direction though, and some ideas to try out.希望这可以让您朝着正确的方向开始,并尝试一些想法。

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

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