如何编辑这个python脚本来自动应用excel公式以在打开时显示结果?

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

我有一个通过包 openpyxl 打开的电子表格,我想将特定的公式应用于第 14 行“N”中一直到当前表格底部的每个单元格,但使公式结果在打开文件时应用,因为在当它根据需要填充单元格时,我必须双击单元格并按 Enter 键才能使结果显示在每一行上。

# Load the workbook
workbook = load_workbook(new_filepath)

# Select the sheet 'Inc Multiple Classifications'
sheet = workbook['Inc Multiple Classifications']



# Assuming Table14 starts at cell A1 (adjust as per your actual table location)
start_row = 2
start_col = 14

# Determine the dimensions of the table (adjust based on your table's size)
num_rows = lengthofBCCFile  # Number of rows in Table14
num_cols = 1  # Number of columns in Table14

# Iterate through each cell in the table and apply the formula
for row in range(start_row, start_row + num_rows):
    for col in range(start_col, start_col + num_cols):
        cell = sheet.cell(row=row, column=col)
        # Build the formula string
        formula = f'=TRIM(IFERROR(LET(p, UPPER(SUBSTITUTE(K{row}, " ", "")), n, LEN(p),     LEFT(p, n-3)&" "&RIGHT(p, 3)), ""))'
        # Set the formula to the cell
        cell.value = formula

# Save the workbook
workbook.save(new_filepath)
workbook.close()

这是打开文件时返回的结果,显示 N 列单元格中的公式,但是直到我双击该单元格并按 Enter 键后才显示结果。

enter image description here

python openpyxl
1个回答
0
投票

wb.calculation.calcMode = 'auto'
绝对有效。

我尝试了简单的代码:

将计算模式设置为“手动”

import openpyxl

wb = openpyxl.Workbook()
ws = wb.active
ws["A1"] = "=SUM(1, 1)"

wb.calculation.calcMode = 'manual'
wb.save('test.xlsx')

我得到了这个:(也就是说,

=SUM(1, 1)
没有被评估”。

enter image description here

但是如果我将计算模式设置为“自动”:

import openpyxl

wb = openpyxl.Workbook()
ws = wb.active
ws["A1"] = "=SUM(1, 1)"

wb.calculation.calcMode = 'auto'
wb.save('test.xlsx')

我得到了以下信息: enter image description here

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