我有一个如下所示的 Excel 文档
num value1 value2
1 A 100
2 B
3 c 300
我想迭代value2
对于值超过 200 的值,如果发现值超过 200,则打印value1
。我遇到的最大问题是告诉它在到达包含文本的单元格末尾时停止 for 循环。
我的循环理想情况下是这样的:
while columnA is not empty:
if value2 > 200:
print (value1)
一些注意事项:我使用的是 win32com。ColumnA
我的数据集中永远不会是空白。预先感谢您提供的任何帮助!
编辑:每个文档的行数并不总是相同。我需要它自动停止。抱歉没说得更清楚
考虑使用 Excel 的对象库,特别是它的范围对象 https://msdn.microsoft.com/en-us/library/office/ff838238.aspx or Worksheet.Cells 属性 https://msdn.microsoft.com/en-us/library/office/ff194567.aspx。此外,通常在 Excel VBA 中,您搜索工作表以查找最后一行,然后循环直到到达它:
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
Output
c
c
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)