如何遍历列中的每个单元格并对每个单元格执行操作

How to iterate over each cell in a column and perform an operation on each

我有一个 excel 文档,其中列出了几个 IP 地址,我需要遍历列中的每个单元格并执行 ping 以确定每个 IP 是否已启动。然后我需要将 ping 函数的结果写入文本文件。

所以在电子表格中,从 A1 开始的 A 列将是:

10.10.10.10
20.20.20.20
30.30.30.30
40.40.40.40

脚本应该读取每一行,ping 每个 IP 地址,然后写入文本文件“10.10.10.10。已启动,20.20.20.20 已关闭”等

import os
import openpyxl
import time


wb = openpyxl.load_workbook('IPS.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
with open(time.strftime("%d-%m-%Y") + "-Decom.txt", "w") as s:
    for i in range(1, sheet.max_row):
        response = os.system("ping -n 2" + sheet[i].value )
        if response == 0:
            s.write(sheet[i].value, 'is up')
        else:
            s.write(sheet[i].value, 'is down')

c:\Python35\Scripts>python ping.py Traceback (most recent call last): File "ping.py", line 10, in response = os.system("ping -n 2" + sheet[i].value ) AttributeError: 'tuple' object has no attribute 'value'

当您执行 sheet[i].value 时,sheet[i] 会 return 一行单元格值的元组。

不过,有一种更简单的方法可以迭代特定列的单元格:

for cell in sheet['A']:        
    value = cell.value

    response = os.system("ping -n 2" + value)
    s.write(value, 'is up' if response == 0 else 'is down')