[英]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.我是 Python 的新手,没有真正的编码知识并且被卡住了。 I have an excel spreadsheet.
我有一个 excel 电子表格。 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").
我有第二列,标题为结果,公式 =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.
如何使用 Python 将这个公式向下迭代到 Outcome 列的多行。
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.此外,如果您能以某种方式获取工作表的行数,并将其分配给
last_row
变量,您可以改进/自动化,而不是像我在示例中那样对其进行硬编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.