Reputation: 21
I have an excel document that I am reading, it has an unknown number of lines, I want to add each line and the three values of columns A B and C into a list and then stop once I reach none. I then want to run an action on each item in the list.
I am terrible with if/for loops
if someone could help.
Below is loading argument 3 as the workbook and sheet. I need to start at line A61
and add A61,B61,C61
to a list and keep going until A whatever is = to none.
Alright so I got this far, now how do I run a command for each item in the row?
if len(sys.argv) > 3:
wb = xlrd.open_workbook(sys.argv[3])
sheet = wb.sheet_by_index(0)
first_kvm_ip = str(sheet.cell_value(34,1))
last_kvm_ip = str(sheet.cell_value(35,1))
kvm_netmask = str(sheet.cell_value(36,1))
rows = sheet.nrows
curr_row = 52
while (curr_row < rows - 1):
curr_row += 1
row1 = int(sheet.cell_value(curr_row,0))
row2 = str(sheet.cell_value(curr_row,1))
vlanls1.append(row1)
vlanls2.append(row2)
I want to run a command for each item in row1 vlan create(row1,row2)
I assume I need a for i iteration. I just need help with that.
I need to run this command for each iteration of row1 and row2
mo = FabricVlan(parent_mo_or_dn="fabric/lan", sharing="none", name=row2, id=row1, mcast_policy_name="", policy_owner="local", default_net="no", pub_nw_name="", compression_type="included")
handle.add_mo(mo)
Alright I think I finally got it. Thanks for the help guys.
if len(sys.argv) > 3:
wb = xlrd.open_workbook(sys.argv[3])
sheet = wb.sheet_by_index(0)
first_kvm_ip = str(sheet.cell_value(34,1))
last_kvm_ip = str(sheet.cell_value(35,1))
kvm_netmask = str(sheet.cell_value(36,1))
rows = sheet.nrows
curr_row = 52
while (curr_row < rows - 1):
curr_row += 1
row1 = int(sheet.cell_value(curr_row,0))
row2 = str(sheet.cell_value(curr_row,1))
vlanls1.append(row1)
vlanls2.append(row2)
for x,y in zip(vlanls1,vlanls2):
mo = FabricVlan(parent_mo_or_dn="fabric/lan", sharing="none", name=y, id=x, mcast_policy_name="", policy_owner="local", default_net="no", pub_nw_name="", compression_type="included")
handle.add_mo(mo)
Upvotes: 2
Views: 281
Reputation: 440
worksheet.rows
returns a list of all rows, no matter how many there are. Each row in that list is itself a list of the cells in that row. Knowing this, it would be fairly easy to implement a for
loop that iterates through each row and appends the first three cells to a new list.
This code should do the trick.
myList = []
for row in sheet.rows:
myList.append([row[0],row[1],row[2]])
I do recommend going through the openpyxl documentation though, it will avoid you some trouble to come. Also, read up on the way that for loops work if you know you have trouble with them :)
http://openpyxl.readthedocs.io/en/default/index.html
http://www.tutorialspoint.com/python/python_for_loop.htm
Upvotes: 1