只读具有值python win32com的Excel单元格 [英] Read only Excel Cells with values python win32com

查看:50
本文介绍了只读具有值python win32com的Excel单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的Excel文档

  num value1 value21 A 1002个3 c 300 

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

理想情况下,我的循环是这样的:

 ,而columnA不为空:如果value2>200:打印(值1) 

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

对于每个文档,我将不会总是具有相同数量的行.我需要它自动停止.抱歉,不清楚!

解决方案

考虑使用Excel的对象库,特别是其

Python COM代码 (使用try/except/finally始终释放资源而不管是否出错)

 将win32com.client导入为win32尝试:f ="myWorkbook.xlsx"xl = win32.gencache.EnsureDispatch('Excel.Application')wb = xl.Workbooks.Open(f)ws = wb.Worksheets(1)xlUp = -4162lastrow = ws.Cells(ws.Rows.Count,"A").End(xlUp).Row + 1对于我在范围(2,最后一行)中的我:#LOOP RANGE OBJ如果ws.Range("C" + str(i)).Value不为None,而ws.Range("C" + str(i)).Value>200:print(ws.Range("B" + str(i)).Value)#LOOP CELLS OBJ如果ws.Cells(i,3).Value不为None并且ws.Cells(i,3).Value>200:打印(ws.Cells(i,2).Value)wb.Close(假)退出例外,例如e:打印(e)最后:ws =无wb =无xl =无 

输出

  cC 

I have an Excel Document like the following

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. 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.

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. ColumnA will never be blank within my data set. 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. Also, usually in Excel VBA, you search the worksheet to find the last row and then loop until you reach it:

Excel worksheet

Python COM Code (using try/except/finally to always release resources regardless of error or not)

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

这篇关于只读具有值python win32com的Excel单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆