如何将Excel行放入列表中

时间:2019-03-24 13:01:42

标签: excel python-2.7 list row

我有一个Excel工作表,其中包含要尝试导出到文本板中的参数。

site name    site      site1     site2     site2
host       hostname  hostname1 hostname2 hostname2
ip          x.x.x.x    x.x.x.x  x.x.x.x   x.x.x.x
sh#             1          1        1         2
ILAN in       yes         yes      no        no
ilan out       no          no      no        no

我想要的是获取每个站点/主机的信息,并将其放入文本板中,每个主机名一个文本板。在此示例中,有4个主机,因此有4个文本板。

文本板名称site-hostname-SH#并在文本板中:

host = hostname
ip = x.x.x.x 
SH# = 1 or 2
ILAN IN = yes or no
ILAN out = yes or no

我能够找到诸如host之类的关键字,但是无法将该行放入列表中。我正在使用文本板作为另一个脚本的全局变量。 excel是信息的来源,而我的其他脚本telnet则是在设备中进行配置的。现在,我必须手动更改每个架子的所有变量,并要自动从excel工作表中更改变量。

import openpyxl
from openpyxl import load_workbook
from openpyxl import Workbook
from Tkinter import Tk
from tkFileDialog import askopenfilename
import sys
import warnings

if not sys.warnoptions:
    warnings.simplefilter("ignore")
#opens filechooser for excel workbook
Tk().withdraw()
filename = askopenfilename()
print ("Working, please be patient")
wb = openpyxl.load_workbook(filename)

#lists worksheets in workbook to pick which worksheet to import
print ("\r")
count = 0
for ws in wb.worksheets:
    tlist = ws.title
    print count,tlist
    count = count + 1

x = input ("\nchoose number:\n")
ws = wb.worksheets[x]
print (ws)

#will eventually put into a function
#finds keyword, in this case site name
for row in ws.iter_rows():
    for cell in row:
        try:
            if cell.value == "Site Name":
                print ("yes")
                print ("TRUE")
                print cell.row, cell.column
                row = cell.row
                column = cell.column
                print column

                site = ws.cell(row = row, column = column)
                print ("this is: %s" %(site.value) )

                print ("this is row %s" %row)
                print row
                print column
        except (AttributeError):
            continue

have tried:
#print ("this is row: %s" %(row) )
##print(row)
#print (SiteName[1])

##x = ws.max_row + 1
##x = int(row)
##for r in range(x, column + 1):
##    d=ws.cell(row=x,column=r)
##    print(d.value)
##print ("this is the row number: %s" %(row) )
##print str(row)
##print ("this is: %s" %(site.value) )
##for i in range(row, col + 1): 
##    cell_obj = ws.cell(row = row, column = i) 
##    print(cell_obj.value)

1 个答案:

答案 0 :(得分:0)

这是您想要的吗?

for row in ws.iter_rows():
    keyword = row[0].value
    values = [item.value for item in row[1:]]
    if keyword == 'site name':
        print(keyword)
        print(values)
        print('-----\n')
        # do whatever you want here