我正在尝试使用具有 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`
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)