简体   繁体   中英

how do I iterate an excel formula down multiple rows using python

I an very new to Python,have no real coding knowledge and am stuck. I have an excel spreadsheet. The first column heading is Land Data. Land data has either Allotment or Farm listed underneath it. I have a second column with the heading Outcome with the formula =IF(A2="Farm","Yes","No").

My code below just does the calculation for the first row. How do I iterate this formula down many rows of the Outcome column using Python.

import openpyxl
wb = openpyxl.load_workbook('test.xlsx')
ws1=wb.active
ws1["C2"]= '=IF(A2="farm","Yes","No")'
wb.save('test.xlsx')

If you know the number of rows you want to change you could do something like:

import openpyxl
wb = openpyxl.load_workbook('test.xlsx')
ws1 = wb.active

last_row = 10  # For example

for i in range(2, last_row):
    cell = "C" + str(i)
    a_cell = "A" + str(i)
    ws1[cell] = '=IF(' + a_cell + '="farm","Yes","No")'
wb.save('test.xlsx')

You basically iterate over each one of the rows and create the formula for each one of those.

Also, you could improve/automatice that if you can somehow get the quantity of rows your sheet has, and assign that to the last_row variable, instead of hardcoding it like I did in the example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM