简体   繁体   English

如何使用 python 向下多行迭代 excel 公式

[英]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.

相关问题 如何在 Excel 中读取公式并将其转换为在 Python 中进行计算? - How do I read in a Formula in Excel and convert it to do the computation in Python? 如何使用 pandas 编写 python 脚本来迭代具有多张工作表的 Excel.xlsx 文件? - How can I write a python scripts using pandas to iterate over Excel .xlsx files with multiple sheets? 如何遍历 excel 文件表并在 Python 中插入公式? - How can I iterate through excel files sheets and insert formula in Python? 如何重新创建一个在Python中调用TREND()的Excel公式? - How do I recreate an Excel formula which calls TREND() in Python? 如何遍历 Python 中的 Excel 电子表格行? - How to iterate through excel spreadsheet rows in Python? 如何使用 Python 遍历 excel 中的列和行? - How to iterate through columns and rows in excel with Python? 如何使用python遍历多个excel文件 - How to iterate through multiple excel files using python 在Python中,如何遍历稀疏矩阵的行? - In Python, how do I iterate over the rows of a sparse matrix? 如何在 Python 中使用 Openpyxl 对多行的 excel 行进行平均? - How to average across excel rows for multiple rows using Openpyxl in Python? 在 python 中跨多行求解公式(类似于 excel)? - Solving formula across multiple rows (similar to excel) in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM