在 Excel 中使用 Python 自动填充公式

安转Python包的国内镜像源

复制代码
清华大学
https://pypi.tuna.tsinghua.edu.cn/simple
 
阿里云
https://mirrors.aliyun.com/pypi/simple/
 
豆瓣
https://pypi.douban.com/simple/ 
 
百度云
https://mirror.baidu.com/pypi/simple/
 
中科大
https://pypi.mirrors.ustc.edu.cn/simple/
 
华为云
https://mirrors.huaweicloud.com/repository/pypi/simple/
 
腾讯云
https://mirrors.cloud.tencent.com/pypi/simple/

准备工作

首先,确保你已经安装了 openpyxl 库。如果还没有安装,可以使用以下命令进行安装:

复制代码
pip install openpyxl

步骤 1:导入必要的库

首先,我们需要导入 openpyxl 库中的 load_workbookTranslator 类。

复制代码
from openpyxl import load_workbook
from openpyxl.formula.translate import Translator

步骤 2:定义填充公式的函数

接下来,我们定义一个名为 fill_down_formulas 的函数。这个函数接受以下参数:

  • filepath:Excel 文件的路径。
  • sheetname:工作表名称。
  • start_row:开始填充公式的行号。
  • start_column:开始填充公式的列号。
  • num_columns:需要填充公式的列数。
复制代码
def fill_down_formulas(filepath, sheetname, start_row, start_column, num_columns):
    try:
        # 加载 Excel 文件
        wb = load_workbook(filename=filepath)
        ws = wb[sheetname]

步骤 3:获取起始单元格的公式

在指定的列范围内,我们首先获取起始单元格的公式。

复制代码
        # 循环处理每一列
        for column_index in range(start_column, start_column + num_columns):
            # 获取起始单元格的公式
            formula = ws.cell(row=start_row, column=column_index).value
            print(f"原始公式 ({start_row}, {column_index}):", formula)

步骤 4:向下填充公式

从起始行的下一行开始,我们将公式填充到该列的其余单元格中。这里使用 Translator 类来更新公式。

复制代码
            # 从起始行开始填充公式
            for row in range(start_row + 1, ws.max_row + 1):
                # 获取起始单元格和当前单元格的坐标
                start_coordinate = ws.cell(row=start_row, column=column_index).coordinate
                current_coordinate = ws.cell(row=row, column=column_index).coordinate
                print("起始坐标:", start_coordinate)
                print("当前坐标:", current_coordinate)

                # 使用 Translator 解析并更新公式
                translated_formula = Translator(formula, origin=start_coordinate).translate_formula(current_coordinate)
                print("翻译后的公式:", translated_formula)
                ws.cell(row=row, column=column_index).value = translated_formula

步骤 5:保存修改后的 Excel 文件

填充完公式后,保存修改后的 Excel 文件。

复制代码
        # 保存修改后的 Excel 文件
        wb.save(filepath)
        print(f"成功向下填充公式到第 {start_column} 列到第 {start_column + num_columns - 1} 列,起始行 {start_row}")
    except Exception as e:
        print(f"填充公式时出错: {e}")

步骤 6:执行脚本

在脚本的最后,我们指定 Excel 文件路径、工作表名称、起始行、起始列和列数,并调用 fill_down_formulas 函数。

复制代码
if __name__ == "__main__":
    # 指定 Excel 文件路径、工作表名、起始行、起始列和列数
    excel_file_path = "C:\\Users\\Administrator\\Desktop\\销售系数数据同步.xlsx"
    sheet_name = "商品费用"
    start_row = 2  # 指定起始行
    start_column = 47  # 指定起始列
    num_columns = 7  # 指定要填充公式的列数

    # 调用函数将公式向下填充到指定列和起始行之后
    fill_down_formulas(excel_file_path, sheet_name, start_row, start_column, num_columns)

完整代码

复制代码
from openpyxl import load_workbook
from openpyxl.formula.translate import Translator

def fill_down_formulas(filepath, sheetname, start_row, start_column, num_columns):
    try:
        # 加载 Excel 文件
        wb = load_workbook(filename=filepath)
        ws = wb[sheetname]

        # 循环处理每一列
        for column_index in range(start_column, start_column + num_columns):
            # 获取起始单元格的公式
            formula = ws.cell(row=start_row, column=column_index).value
            print(f"原始公式 ({start_row}, {column_index}):", formula)

            # 从起始行开始填充公式
            for row in range(start_row + 1, ws.max_row + 1):
                # 获取起始单元格和当前单元格的坐标
                start_coordinate = ws.cell(row=start_row, column=column_index).coordinate
                current_coordinate = ws.cell(row=row, column=column_index).coordinate
                print("起始坐标:", start_coordinate)
                print("当前坐标:", current_coordinate)

                # 使用 Translator 解析并更新公式
                translated_formula = Translator(formula, origin=start_coordinate).translate_formula(current_coordinate)
                print("翻译后的公式:", translated_formula)
                ws.cell(row=row, column=column_index).value = translated_formula

        # 保存修改后的 Excel 文件
        wb.save(filepath)
        print(f"成功向下填充公式到第 {start_column} 列到第 {start_column + num_columns - 1} 列,起始行 {start_row}")
    except Exception as e:
        print(f"填充公式时出错: {e}")

if __name__ == "__main__":
    # 指定 Excel 文件路径、工作表名、起始行、起始列和列数
    excel_file_path = "C:\\Users\\Administrator\\Desktop\\销售系数数据同步.xlsx"
    sheet_name = "商品费用"
    start_row = 2  # 指定起始行
    start_column = 47  # 指定起始列
    num_columns = 7  # 指定要填充公式的列数

    # 调用函数将公式向下填充到指定列和起始行之后
    fill_down_formulas(excel_file_path, sheet_name, start_row, start_column, num_columns)
相关推荐
紫雾凌寒42 分钟前
计算机视觉 |解锁视频理解三剑客——TimeSformer
python·深度学习·神经网络·计算机视觉·transformer·timesformer
程序员杰哥1 小时前
测试用例详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
go54631584657 小时前
本地部署 GitHub 上的 Python 人脸识别项目
开发语言·python·github
FreakStudio8 小时前
手把手教你用 MicroPython 玩转幻尔串口舵机,代码+教程全公开
python·嵌入式·大学生·面向对象·技术栈·电子diy·电子计算机
tekin8 小时前
基于 Python 开发在线多人游戏服务器案例解析
服务器·python·游戏·在线多人游戏服务器
让学习成为一种生活方式10 小时前
libGL.so.1: cannot open shared object file: No such file or directory-linux022
linux·开发语言·python
java1234_小锋10 小时前
一周学会Flask3 Python Web开发-Jinja2模板继承和include标签使用
python·flask·flask3
图书馆钉子户11 小时前
from flask_session import Session 为什么是Session(app)这么用?
python·flask·mybatis
一只蜗牛儿11 小时前
Sherpa-ONNX:说话人识别与语音识别自动开启(VAD)+ Python API 完整指南
人工智能·python·语音识别
结衣结衣.11 小时前
【OpenCV】入门教学
图像处理·人工智能·python·opencv