You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用Python复制带公式的Excel多列并插入到指定目录下多个工作簿时的公式保留问题

求助:使用Python复制带公式的Excel多列并插入到指定目录下多个工作簿时的公式保留问题

我最近在做一个Excel批量处理的需求:需要把某一个Excel文件里指定的几列(这些列里有的单元格是带公式的)复制出来,然后插入到根目录下所有其他Excel工作簿的指定位置里。

目前不带公式的列我已经能顺利完成复制和插入了,但一碰到带公式的列就出问题——不仅没法正常插入,还一直弹出错误:An error occurred: 'Cell' object has no attribute 'formula'。

我把自己写的代码贴在下面,有没有大佬能帮我看看哪里出问题了?怎么修改才能保留公式,顺利完成带公式列的批量复制插入呢?

import pandas as pd 
import openpyxl 
import os 
from openpyxl.utils import get_column_letter

def copy_columns_with_formulas_to_multiple_excel(source_file, source_columns, root_dir, dest_columns, source_sheet=None, dest_sheet=None): 
    """ Copies specified columns with formulas from a source Excel file to specific columns in multiple Excel files within a root directory (and its subdirectories).

    Args:
        source_file (str): Path to the source Excel file.
        source_columns (list): List of column names or indices to copy from the source.
        root_dir (str): Path to the root directory containing the destination Excel files.
        dest_columns (list): List of column names or indices to paste into the destination.
        source_sheet (str, optional): Name of the sheet in the source file. Defaults to None (first sheet).
        dest_sheet (str, optional): Name of the sheet in the destination files. Defaults to None (first sheet).
    """
    try:
        if not source_file.endswith(('.xlsx', '.xls')):
            raise ValueError("Source file must be an Excel file (.xlsx or .xls).")

        source_wb = openpyxl.load_workbook(source_file)
        source_ws = source_wb[source_sheet] if source_sheet else source_wb.active

        if len(source_columns) != len(dest_columns):
            raise ValueError("Number of source and destination columns must be the same.")

        for root, _, files in os.walk(root_dir):
            for file in files:
                if file.endswith(('.xlsx', '.xls')) and os.path.join(root, file) != os.path.abspath(source_file): # prevent source file from being modified.
                    dest_file_path = os.path.join(root, file)
                    try:
                        dest_wb = openpyxl.load_workbook(dest_file_path)
                        dest_ws = dest_wb[dest_sheet] if dest_sheet else dest_wb.active

                        for source_col, dest_col in zip(source_columns, dest_columns):
                            if isinstance(source_col, str):
                                source_col_index = openpyxl.utils.column_index_from_string(source_col)
                            else:
                                source_col_index = source_col + 1

                            if isinstance(dest_col, str):
                                dest_col_index = openpyxl.utils.column_index_from_string(dest_col)
                            else:
                                dest_col_index = dest_col + 1

                            for row in range(1, source_ws.max_row + 1):
                                cell = source_ws.cell(row=row, column=source_col_index)
                                dest_ws.cell(row=row, column=dest_col_index).value = cell.value
                                if cell.formula:
                                    dest_ws.cell(row=row, column=dest_col_index).formula = cell.formula

                        dest_wb.save(dest_file_path)
                        print(f"Columns with formulas copied to '{dest_file_path}', sheet '{dest_sheet if dest_sheet else 'first sheet'}'.")

                    except Exception as e:
                        print(f"Error processing '{dest_file_path}': {e}")
        print("Copy process completed.")

    except FileNotFoundError:
        print(f"Error: Source file or root directory not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

source_file = r"C:\Users\xxx\Documents\Source File.xlsx" 
source_columns = [1,3] 
root_directory = r"C:\Users\xxx\Documents\Test" #replace with your directory
dest_columns = [5,6] 
source_sheet = "Sheet1" 
dest_sheet = "Sheet1"

copy_columns_with_formulas_to_multiple_excel(source_file, source_columns, root_directory, dest_columns, source_sheet, dest_sheet)

备注:内容来源于stack exchange,提问作者Bryan Parr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 11:28:03