简体   繁体   English

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

[英]Read only Excel Cells with values python win32com

I have an Excel Document like the following 我有一个如下的Excel文档

num value1 value2

1       A      100
2       B      
3       c      300

I want to iterate through value2 for something with a value of over 200, and if it finds a value over 200, print value1 . 我想遍历value2以获得超过200的值,如果发现超过200的值,则打印value1 The big thing I'm having an issue with is telling it to stop the for loop once it reaches the end of the cells with text in it. 我遇到的一个大问题是告诉它在到达带有文本的单元格末尾时停止for循环。

My loop would ideally be something like this: 我的循环最好是这样的:

while columnA is not empty:
     if value2 > 200:
           print (value1)

a few notes: I'm using win32com. 一些注意事项:我正在使用win32com。 ColumnA will never be blank within my data set. 在我的数据集中, ColumnA永远不会为空。 Thank you in advance for any help you can provide! 预先感谢您提供的任何帮助!

Edit: I will not always have the same number of rows for each document. 编辑:每个文档的行数不会总是相同。 I need it to automatically stop. 我需要它自动停止。 Sorry for not being clearer 抱歉,不清楚

Consider using Excel's object library, specifically its Range Object or Worksheet.Cells Property . 考虑使用Excel的对象库,特别是其Range ObjectWorksheet.Cells属性 Also, usually in Excel VBA, you search the worksheet to find the last row and then loop until you reach it: 同样,通常在Excel VBA中,您搜索工作表以找到最后一行,然后循环直到找到为止:

Excel worksheet Excel工作表

Excel工作表

Python COM Code (using try/except/finally to always release resources regardless of error or not) 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

Output 输出量

c
c

I am not sure how are you parsing fro the excel file, but if you are using xlrd module I think something like this might work. 我不确定如何从excel文件解析,但是如果您使用的是xlrd模块,我认为类似的方法可能会起作用。

    workbook = xlrd.open_workbook('read_file.xlsx')

    worksheet = workbook.sheet_by_index(0)

    for i in range(1,4):
        if worksheet.cell(i, 2).value > 200:
            print worksheet.cell(i,1)

for the loop range I think you can specify the number of rows but I don't remember that right now. 对于循环范围,我认为您可以指定行数,但我现在不记得了。

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

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