繁体   English   中英

如何在python中的excel中自动填充公式?

[英]How to autofill formulas in excel in python?

我正在尝试自动填充 D 列中的公式,图像是预期的输出。 在此处输入图像描述

我的代码如下。 如您所见,我正在尝试使用循环和列表来完成操作。

import pandas as pd
from openpyxl import load_workbook

#Pick the excel file I want to edit.
file_source =r'C:\Users\user\Desktop\BB\Data.xlsx'
#The number of items in column "iso2"
row_len = len(pd.read_excel(file_source,sheet_name='new_sheet', usecols=['iso2']))

#Make the list of formula which I want to autofill in column "iso2" in excel file.
row_len_list=[]
for i in range(row_len):
    j=str(i)
    row_len_list.append(j)
index_formula_list=[]
for x in row_len_list[2:len(row_len_list)]:
    #The formula
    k='=VLOOKUP(A'+x+',old_sheet!A:G,7,0)+200/C'+x
    index_formula_list.append(k)

#load excel file
workbook = load_workbook(filename=file_source)

#Pick the sheet "new_sheet"
ws4 = workbook["new_sheet"]    

#Autofill the formula
for g in range(2,row_len):
    for o in index_formula_list:
        ws4.cell(row=g,column=4).value=o
        workbook.save(filename=file_source)

然而,它陷入了一个循环,永远不会结束。 请帮我找出错误。

请在下面找到更新的代码。 我减少了一些代码,因为您不需要read_excel和单独的循环来创建数组等。希望这可行....

import pandas as pd
from openpyxl import load_workbook

#Pick the excel file I want to edit.
file_source =r'C:\Users\user\Desktop\BB\Data.xlsx'

#load excel file
workbook = load_workbook(filename=file_source)

#Pick the sheet "new_sheet"
ws4 = workbook["new_sheet"]    

#Get length of col A
row_len=len(ws4['A'])

#Autofill the formula
for g in range(2,row_len+1):
    k='=VLOOKUP(A'+str(g)+',old_sheet!A:G,7,0)+200/C'+str(g)
    ws4.cell(row=g,column=4).value=k

workbook.save(filename=file_source)

运行代码后new_sheet的输出

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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