只读具有值的 Excel 单元格 python win32com

nic*_*ico 3 python excel win32com

我有一个像下面这样的 Excel 文档

num value1 value2

1       A      100
2       B      
3       c      300
Run Code Online (Sandbox Code Playgroud)

我想遍历value2值超过 200 的值,如果发现值超过 200,则打印value1。我遇到的最大问题是告诉它一旦到达带有文本的单元格的末尾就停止 for 循环。

我的循环最好是这样的:

while columnA is not empty:
     if value2 > 200:
           print (value1)
Run Code Online (Sandbox Code Playgroud)

一些注意事项:我正在使用 win32com。ColumnA在我的数据集中永远不会是空白的。预先感谢您提供的任何帮助!

编辑:对于每个文档,我不会总是有相同的行数。我需要它自动停止。抱歉没说清楚

Par*_*ait 6

考虑使用 Excel 的对象库,特别是它的Range ObjectWorksheet.Cells Property。此外,通常在 Excel VBA 中,您搜索工作表以找到最后一行,然后循环直到到达它:

Excel 工作表

Excel 工作表

Python COM 代码 (使用 try/except/finally 始终释放资源,无论是否出错)

import win32com.client as win32

try:
    f = "myWorkbook.xlsx"
    xl = win32.gencache.EnsureDispatch('Excel.Application')
    wb = xl.Workbooks.Open(f)
    ws = wb.Worksheets(1)

    xlUp = -4162
    lastrow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1

    for i in range(2,lastrow):
        # LOOP RANGE OBJ
        if ws.Range("C" + str(i)).Value is not None and ws.Range("C" + str(i)).Value > 200:
            print(ws.Range("B" + str(i)).Value)

        # LOOP CELLS OBJ
        if ws.Cells(i,3).Value is not None and ws.Cells(i,3).Value > 200:
            print(ws.Cells(i,2).Value)

    wb.Close(False)
    xl.Quit

except Exception as e:
    print(e)

finally:
    ws = None
    wb = None
    xl = None
Run Code Online (Sandbox Code Playgroud)

输出

c
c
Run Code Online (Sandbox Code Playgroud)