合并多个excel到一个excel中
问题描述:读取文件夹中所有xlsx文件把所有文件中数据合并到一个xlsx文件中,以文件名作为每一个工作簿的名字,做到完全复制表格中所有格式,颜色等,粘贴到新表。
思路:利用openpyxl模块,完全复制:单元格格式,字体,颜色等到新创建的汇总表格中。
import os
from openpyxl import load_workbook, Workbook
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment, Protection
from openpyxl.utils import get_column_letterdef copy_cell_style(source_cell, target_cell):"""复制单个单元格的所有样式(字体、颜色、边框、对齐等)"""# 1. 复制字体(字体类型、大小、颜色、加粗/斜体等)target_cell.font = Font(name=source_cell.font.name,size=source_cell.font.size,bold=source_cell.font.bold,italic=source_cell.font.italic,underline=source_cell.font.underline,color=source_cell.font.color)# 2. 复制填充色(背景色)if source_cell.fill.fgColor.rgb:target_cell.fill = PatternFill(fill_type=source_cell.fill.fill_type,fgColor=source_cell.fill.fgColor,bgColor=source_cell.fill.bgColor)# 3. 复制边框(上下左右边框的样式、颜色)target_cell.border = Border(left=Side(style=source_cell.border.left.style, color=source_cell.border.left.color),right=Side(style=source_cell.border.right.style, color=source_cell.border.right.color),top=Side(style=source_cell.border.top.style, color=source_cell.border.top.color),bottom=Side(style=source_cell.border.bottom.style, color=source_cell.border.bottom.color))# 4. 复制对齐方式(水平/垂直对齐、换行、缩进等)target_cell.alignment = Alignment(horizontal=source_cell.alignment.horizontal,vertical=source_cell.alignment.vertical,wrap_text=source_cell.alignment.wrap_text,indent=source_cell.alignment.indent)# 5. 复制其他属性(数字格式、保护状态)target_cell.number_format = source_cell.number_formattarget_cell.protection = Protection(locked=source_cell.protection.locked,hidden=source_cell.protection.hidden)def copy_merged_cells(source_sheet, target_sheet):"""复制合并单元格设置"""for merged_range in source_sheet.merged_cells.ranges:target_sheet.merge_cells(str(merged_range))def merge_excel_files(folder_path, output_filename="合并后的Excel.xlsx"):"""合并文件夹中所有XLSX文件到新文件:param folder_path: 源Excel文件所在文件夹路径:param output_filename: 输出文件名(默认:合并后的Excel.xlsx)"""# 1. 创建新的Excel工作簿new_wb = Workbook()# 删除默认的"Sheet"工作表(避免冗余)default_sheet = new_wb.activenew_wb.remove(default_sheet)# 2. 遍历文件夹中的所有文件for filename in os.listdir(folder_path):# 只处理.xlsx文件,且排除输出文件(避免重复)if filename.endswith(".xlsx") and filename != output_filename:# 获取文件完整路径file_path = os.path.join(folder_path, filename)# 工作表名称 = 文件名(去掉.xlsx后缀)sheet_name = os.path.splitext(filename)[0]# 工作表名称不能超过31个字符if len(sheet_name) > 31:sheet_name = sheet_name[:31]try:# 3. 打开源Excel文件(read_only=False才能读取样式)source_wb = load_workbook(file_path, read_only=False, data_only=False)# 读取源文件的第一个工作表source_sheet = source_wb.active# 4. 在新文件中创建工作表(以文件名命名)new_sheet = new_wb.create_sheet(title=sheet_name)# 5. 复制源工作表的所有单元格(数据+样式)for row in source_sheet.iter_rows(values_only=False):for source_cell in row:# 跳过合并单元格(只处理原始单元格)if source_cell.coordinate in source_sheet.merged_cells:continue# 获取目标单元格位置target_cell = new_sheet[source_cell.coordinate]# 复制单元格内容target_cell.value = source_cell.value# 复制单元格样式copy_cell_style(source_cell, target_cell)# 6. 复制合并单元格设置copy_merged_cells(source_sheet, new_sheet)# 7. 复制列宽(保证格式一致)- 修改部分# 遍历列索引而非列对象,避免处理合并单元格for col_idx in range(1, source_sheet.max_column + 1):col_letter = get_column_letter(col_idx)if col_letter in source_sheet.column_dimensions:new_sheet.column_dimensions[col_letter].width = source_sheet.column_dimensions[col_letter].width# 8. 复制行高(保证格式一致)for row_num in range(1, source_sheet.max_row + 1):if row_num in source_sheet.row_dimensions:new_sheet.row_dimensions[row_num].height = source_sheet.row_dimensions[row_num].heightprint(f"✅ 成功合并:{filename}(工作表名:{sheet_name})")source_wb.close() # 关闭源文件,释放资源except Exception as e:print(f"❌ 合并失败:{filename},错误原因:{str(e)}")# 9. 保存合并后的新文件(路径=源文件夹+输出文件名)output_path = os.path.join(folder_path, output_filename)new_wb.save(output_path)print(f"\n🎉 所有文件合并完成!新文件路径:{output_path}")# -------------------------- 请修改这里的路径 --------------------------
# 替换为你的Excel文件所在文件夹路径
folder_path = os.getcwd() # 示例:Windows路径
# folder_path = "/Users/xxx/Excel合并" # 示例:Mac/Linux路径# 执行合并函数
merge_excel_files(folder_path)