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

如何高效实现Excel文件数据追加?现有方案耗时9秒求优化

高效实现Excel大文件数据追加需求

需求说明

需将folder1中Excel file1指定工作表的数据,追加到folder2中Excel file2的对应工作表,两者数据量均较大。当前代码执行耗时9秒,目标是将耗时压缩至2-3秒。

当前实现代码

import pandas as pd
import time
from openpyxl import load_workbook

# 定义输入输出Excel文件路径
input_file_path = 'path_to_input_folder/input_file.xlsx'
output_file_path = 'path_to_output_folder/output_file.xlsx'
n = 100  # 替换为需要追加的记录数

# 记录开始时间
start_time = time.time()

# 读取输入Excel文件
with pd.ExcelFile(input_file_path) as input_excel:
    input_data = pd.read_excel(input_excel)

# 加载已有的输出Excel文件
output_excel = load_workbook(output_file_path)

# 选择"Sheet1"工作表
output_sheet = output_excel['Sheet1']

# 将输入数据的前n条记录追加到现有"Sheet1"中
for row in input_data.head(n).values:
    output_sheet.append(row.tolist())

# 保存修改后的输出Excel文件
output_excel.save(output_file_path)

# 计算并显示执行时间
execution_time = time.time() - start_time
print(f"执行时间: {execution_time:.2f} 秒")

优化方案

方案1:Pandas批量写入(跨平台通用最优解)

原代码瓶颈在于逐行循环写入,改用Pandas的ExcelWriter批量写入,将IO操作从n次压缩为1次,速度可提升3-5倍。

import pandas as pd
import time

input_file_path = 'path_to_input_folder/input_file.xlsx'
output_file_path = 'path_to_output_folder/output_file.xlsx'
n = 100

start_time = time.time()

# 仅读取输入文件的前n行数据,减少内存占用
input_data = pd.read_excel(input_file_path, nrows=n)

# 以追加模式打开输出文件,指定覆盖工作表(仅追加数据)
with pd.ExcelWriter(
    output_file_path,
    mode='a',
    engine='openpyxl',
    if_sheet_exists='overlay'
) as writer:
    # 获取输出工作表的已有行数,从下一行开始写入
    book = writer.book
    target_sheet = book['Sheet1']
    start_row = target_sheet.max_row
    # 写入数据时跳过表头,避免重复写入
    input_data.to_excel(
        writer,
        sheet_name='Sheet1',
        startrow=start_row,
        header=False,
        index=False
    )

execution_time = time.time() - start_time
print(f"执行时间: {execution_time:.2f} 秒")

方案2:Windows环境下调用Excel原生接口

如果是Windows系统,直接调用Excel COM接口的写入速度更快,适合超大规模文件:

import win32com.client as win32
import time

input_file_path = 'path_to_input_folder/input_file.xlsx'
output_file_path = 'path_to_output_folder/output_file.xlsx'
n = 100

start_time = time.time()

# 后台启动Excel应用
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = False

# 打开输入输出文件
wb_input = excel.Workbooks.Open(input_file_path)
wb_output = excel.Workbooks.Open(output_file_path)

ws_input = wb_input.Sheets('Sheet1')
ws_output = wb_output.Sheets('Sheet1')

# 获取输出表的最后一行位置
last_row = ws_output.Cells(ws_output.Rows.Count, 1).End(-4162).Row  # xlUp对应值为-4162

# 批量复制输入表的前n行数据到输出表(跳过表头)
ws_input.Range(
    ws_input.Cells(2, 1),
    ws_input.Cells(n+1, ws_input.UsedRange.Columns.Count)
).Copy(ws_output.Cells(last_row+1, 1))

# 保存并关闭文件,退出Excel
wb_output.Save()
wb_output.Close()
wb_input.Close()
excel.Quit()

execution_time = time.time() - start_time
print(f"执行时间: {execution_time:.2f} 秒")

优化说明

  • 核心优化点:避免逐行写入的循环开销,改用批量IO操作,这是提升速度的关键。
  • 方案1是跨平台通用方案,无需额外依赖,基本能满足2-3秒的耗时要求;方案2在Windows下性能更优,但需要安装pywin32库。

内容的提问来源于stack exchange,提问作者user21319481

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:13:10