使用 xlwings 将公式添加到表格的列

问题描述 投票:0回答:1

我正在尝试使用具有 2 个表格的 Xlwings 自动化 Excel 工作表。我想在两个表的性能列中添加一个公式,这样如果我将新数据输入到表中,它会自动使用该公式进行计算,我能够对范围执行此操作,但不能对表执行此操作。

`
import xlwings as xw
wb = xw.Book() 
column_name = 'Sales'
formula = '=IF([@[Sales]]<40000, "Bad", IF(AND([@[Sales]]>=40000, [@[Sales]]<=75000), "Neutral", "Good"))'

for table_name in ['Table1', 'Table2'`your text`]:
    wb.sheets[0][f'{table_name}[{column_name}]'].formula = formula`
python excel vba data-science xlwings
1个回答
0
投票
import xlwings as xw
# modify as needed
file_path = r'd:\temp\test.xlsx'
try:
    # get opened workbook by its fullname
    wb = xw.books[file_path]
except:
    # If not found, open the workbook
    wb = xw.Book(file_path)
# Set the column name, modify as needed
column_name = 'flag'
formula = '=IF([@[Sales]]<40000, "Bad", IF(AND([@[Sales]]>=40000, [@[Sales]]<=75000), "Neutral", "Good"))'
# Iterate through table names and set the formula in each table
for table_name in ['Table1', 'Table2']:
    table_range = wb.sheets[0][f'{table_name}[{column_name}]']
    table_range.formula = formula
# Save the workbook
wb.save(file_path)

© www.soinside.com 2019 - 2024. All rights reserved.