如何从excel表格中查找非空数据的行和列坐标?

2024-10-01 04:49:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试的是获取带有一些颜色格式的excel数据内容,截图并保存图像

我的业务逻辑如下所示

def capture_multiple_images():
    capture_image("REPORT_1_NONCOLOR_TEST.xlsx","RSP_TIME.jpeg",13,12)  #upto 13 rows, 12 columns
    capture_image("REPORT_2_NONCOLOR_TEST.xlsx","FID_REPORT.jpeg",6,10)  #upto 6 rows, 10 columns
    capture_image("REPORT_3_NONCOLOR_TEST.xlsx","ERCD_TREND.jpeg",5,7)  #upto 5 rows, 7 columns

捕获图像方法具有以下代码-

def capture_image(EXCEL_FILE,IMAGE_NAME,row,column):
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    workbook = excel.Workbooks.Open(os.path.join(Path.cwd(),EXCEL_FILE))
    ws = workbook.Worksheets['Sheet1']
    ws.Columns.AutoFit()
    ws.Range(ws.Cells(1,1),ws.Cells(row,column)).CopyPicture(Format= win32.constants.xlBitmap)  
    img = ImageGrab.grabclipboard()
    cwd = Path.cwd()
    imgFile = os.path.join(cwd,IMAGE_NAME)
    print(imgFile)
    img.save(imgFile)

如果您注意到我正在从用户处获取行、列。所以我需要基于非空单元格的动态坐标。我不需要每次都提到行、列。因为excel文件的数据是动态的,所以我需要一种方法来获取总行和总列的数据

附件是我的示例数据,如果您看到这里的数据,我需要程序中5行7列的坐标,以便我可以将这些数据传递给我的“capture_image”方法。而不是像这样手动传递

capture_image("REPORT_3_NONCOLOR_TEST.xlsx","ERCD_TREND.jpeg",5,7)

但这是意料之中的

def get_row(excel_file):
    ######
    program to get the total number of rows is having non empty data
    return row_number

def get_column(excel_file):
    ######
    program to get the total number of columns is having non empty data
    return column_number

现在预期的方法调用将如下所示-

capture_image("REPORT_3_NONCOLOR_TEST.xlsx","ERCD_TREND.jpeg",get_row(excel_file),get_column(excel_file))

enter image description here


Tags: 数据testimagereportgetwsdefcolumn
1条回答
网友
1楼 · 发布于 2024-10-01 04:49:45

以下代码解决了我的问题-

from openpyxl import load_workbook
wb = load_workbook("REPORT_3_NONCOLOR_TEST.xlsx")

print(wb.worksheets[0].max_row)
print( (wb.worksheets[0].max_column))

现在我可以这样调用该方法-

capture_image("REPORT_3_NONCOLOR_TEST.xlsx","ERCD_TREND.jpeg",wb.worksheets[0].max_row,wb.worksheets[0].max_column)

相关问题 更多 >