Python 和 Excel - 下拉公式

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

我正在使用 Python 自动化一份报告。 一般来说,我有大约 20 个 Excel 文件(.xlsx 和 .xlms),我根据某些条件对其进行过滤,然后复制并粘贴到最终报告。最后,我在最终报告中下拉/自动填充公式(从第一行到最后) - 我认为这会节省一些准备报告的时间。

下面的代码(版本 1)是下拉/自动填充公式的最佳方式吗?我当然需要保留参考更新(意味着如果我更改单元格、论坛更新 -> AO11、AO12、AO13 等)。 我还测试了另一种方法(版本 2),但随后我在 excel 中收到错误,并且所有公式都被删除...

#Version 1
# Loop over each row in the range
for row in range(start_row, end_row + 1):
    # Adjust the formula for each row
    adjusted_formula = formula_AP10.replace("10", str(row))  # Update the row reference
    adjusted_formula = adjusted_formula.replace("AO10", f"AO{row}")  # Update the AO10 reference   
    adjusted_formula = adjusted_formula.replace("AN10", f"AN{row}")  # Update the AN10 reference
                    
    # Set the adjusted formula to the current cell in column AP
    MPV1[f"AP{row}"].value = adjusted_formula      



#Version 2
from openpyxl import load_workbook

# Load the workbook
wb = load_workbook('_MAT_TEMPLATE_Python.xlsx')
ws = wb["Material prices"]

# Get the total number of rows based on column A
total_rows = sum(1 for row in ws.iter_rows(min_row=7, max_col=1, max_row=ws.max_row, values_only=True) if row[0])

# Apply formulas in column B
for row in range(7, 7 + total_rows):
    # Generate the formula for column B
    formula = f'=VLOOKUP($A{row},"Master data"!$A:$H,2,0)'

    # Apply the formula to the cell
    ws.cell(row=row, column=2, value=formula)

# Save the workbook
wb.save("_MAT_TEMPLATE_Python.xlsx")



#Error that I receive:
recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<logFileName>error148000_01.xml</logFileName>
<summary>Errors were detected in file 'C:\Users\HP\MHL project\_MAT_TEMPLATE_Python.xlsx'</summary>
<removedRecords summary="Following is a list of removed records:">
<removedRecord>Removed Records: Formula from /xl/worksheets/sheet23.xml part</removedRecord>
</removedRecords>
</recoveryLog>
python excel openpyxl
1个回答
0
投票

如果您愿意,可以使用翻译器
在单元格“B7”中输入第一个公式,然后转换为 B 列中的其余单元格。

#Version 3
from openpyxl import load_workbook
from openpyxl.formula.translate import Translator

# Load the workbook
wb = load_workbook('../ExcelFiles/_MAT_TEMPLATE_Python.xlsx')
ws = wb["Material prices"]

# Get the total number of rows based on column A
total_rows = sum(1 for row in ws.iter_rows(max_col=1, max_row=ws.max_row, values_only=True) if row[0])

# Generate the formula for column B
orig_formula = "=VLOOKUP($A7,'Master data'!$A:$H,2,0)"
orig_cell = 'B7'
ws[orig_cell] = orig_formula

# Apply formulas in column B
for row in range(8, total_rows+1):

    dst_cell = f"B{row}"
    # Apply the formula to the cell translating from cell B7
    ws[dst_cell] = Translator(orig_formula, origin=orig_cell).translate_formula(dst_cell)

# Save the workbook
wb.save("../ExcelFiles/_MAT_TEMPLATE_Python.xlsx")
© www.soinside.com 2019 - 2024. All rights reserved.