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

如何用Python将多个.xls文件合并到单个.xls文件的不同工作表中?

合并多个.xls文件到单个文件(每个源文件对应独立工作表)

首先得说一下,你当前的代码是用来处理TXT文件转Excel的,和你想要合并多个XLS文件的需求不匹配,我来给你提供针对性的解决方案:

实现思路

  • 遍历指定目录下所有的.xls文件
  • 创建一个新的目标Excel工作簿
  • 对每个源XLS文件,读取其内容并复制到目标工作簿的新工作表中(工作表可以按顺序命名为Sheet1、Sheet2...,也可以用源文件名命名)
  • 保存目标工作簿

完整代码实现

import os
import xlrd
import xlwt

def is_xls_file(file_path):
    # 判断是否为有效xls文件,排除Excel临时文件(比如~$开头的)
    return file_path.endswith('.xls') and not os.path.basename(file_path).startswith('~$')

def copy_sheet_content(source_workbook, target_workbook, sheet_name):
    # 复制源文件工作表内容到目标工作表
    source_sheet = source_workbook.sheet_by_index(0)  # 默认取源文件第一个工作表
    target_sheet = target_workbook.add_sheet(sheet_name)
    
    # 设置你需要的数字格式
    number_style = xlwt.XFStyle()
    number_style.num_format_str = '#,###0.00'
    
    # 逐行逐列复制内容
    for row_idx in range(source_sheet.nrows):
        for col_idx in range(source_sheet.ncols):
            cell_value = source_sheet.cell_value(row_idx, col_idx)
            # 数字类型应用格式,其他类型直接写入
            if isinstance(cell_value, (int, float)):
                target_sheet.write(row_idx, col_idx, cell_value, number_style)
            else:
                target_sheet.write(row_idx, col_idx, cell_value)

if __name__ == '__main__':
    mypath = input("Please enter the directory path for the input files: ")
    
    # 获取目录下所有有效xls文件
    xls_files = [
        os.path.join(mypath, filename) 
        for filename in os.listdir(mypath) 
        if os.path.isfile(os.path.join(mypath, filename)) and is_xls_file(filename)
    ]
    
    if not xls_files:
        print("No valid .xls files found in the specified directory.")
        exit()
    
    # 创建目标工作簿
    target_workbook = xlwt.Workbook()
    
    # 逐个处理源文件并合并
    for file_index, xls_file in enumerate(xls_files, 1):
        try:
            source_workbook = xlrd.open_workbook(xls_file)
            # 按需求命名工作表,比如1.xls对应Sheet1
            sheet_name = f'Sheet{file_index}'
            # 也可以用源文件名作为工作表名:sheet_name = os.path.basename(xls_file).replace('.xls', '')
            copy_sheet_content(source_workbook, target_workbook, sheet_name)
            print(f"Successfully merged {xls_file} into {sheet_name}")
        except Exception as e:
            print(f"Failed to process {xls_file}: {str(e)}")
    
    # 保存合并后的文件
    target_file = os.path.join(mypath, 'merged_result.xls')
    target_workbook.save(target_file)
    print(f"Merge completed! Result saved to {target_file}")

代码说明

  1. 文件筛选:is_xls_file函数会过滤掉Excel打开时生成的临时文件,只处理真正的.xls文件。
  2. 内容复制:copy_sheet_content函数负责把源文件的第一个工作表内容完整复制到目标工作簿的新工作表,同时保留你需要的数字格式。
  3. 异常处理:添加了异常捕获,避免单个文件处理失败导致整个程序崩溃。
  4. 命名灵活:你可以选择按顺序命名工作表(符合你说的1.xls对应Sheet1),也可以改用源文件名作为工作表名,只需要切换注释行即可。

注意事项

  • 确保已经安装依赖库,执行pip install xlrd xlwt即可完成安装。
  • xlrd 2.0及以上版本仅支持.xls格式,如果你需要处理.xlsx文件,可以改用openpyxl库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:08:38