alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[971] [Keep original formats] Combine multiple Excel files into one Excel file with multiple sheets

If the existing Excel file has special formatting that prevents reading it directly with Pandas, you can use a library like openpyxl to handle the appending of new sheets. Here's how you can achieve this:

import os
from openpyxl import load_workbook
# Path to the existing Excel file
existing_excel_file = 'existing_file.xlsx'
# Path to the folder containing the Excel files to append
folder_path = 'folder_with_excel_files/'
# Load the existing Excel workbook
existing_wb = load_workbook(existing_excel_file)
# Iterate through the Excel files in the folder
for file_name in os.listdir(folder_path):
if file_name.endswith('.xlsx'):
# Construct the full path to the Excel file
file_path = os.path.join(folder_path, file_name)
# Load the Excel workbook to be appended
append_wb = load_workbook(file_path)
# Iterate through sheets in the workbook to be appended
for sheet in append_wb.sheetnames:
# Copy each sheet from the workbook to be appended to the existing workbook
append_sheet = append_wb[sheet]
existing_wb.create_sheet(title=sheet)
existing_sheet = existing_wb[sheet]
for row in append_sheet.iter_rows():
for cell in row:
existing_sheet[cell.coordinate].value = cell.value
# Save the updated existing Excel workbook
existing_wb.save(existing_excel_file)

In this code:

  • existing_excel_file is the path to the existing Excel file.
  • folder_path is the path to the folder containing the Excel files you want to append.
  • We load the existing Excel workbook using openpyxl.load_workbook().
  • We iterate through the Excel files in the specified folder, load each workbook to be appended, and then iterate through its sheets.
  • For each sheet in the workbook to be appended, we create a corresponding sheet in the existing workbook, then copy the values from each cell in the sheet to the corresponding cell in the existing workbook.
  • Finally, we save the updated existing workbook.

posted on   McDelfino  阅读(4)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2021-02-12 【525】GeoServer制作heatmap相关说明
2020-02-12 【459】淘宝添加客服等问题
2019-02-12 【371】Twitter 分类相关
2015-02-12 【159】解决由于google被封导致GoAgent不能使用的办法
点击右上角即可分享
微信分享提示