技术文摘
Python 批量合并同一文件夹内子文件夹 Excel 文件所有 Sheet 数据的四种方法
2024-12-31 03:54:46 小编
Python 批量合并同一文件夹内子文件夹 Excel 文件所有 Sheet 数据的四种方法
在数据处理工作中,我们经常会遇到需要将同一文件夹内子文件夹中的多个 Excel 文件的所有 Sheet 数据进行合并的情况。使用 Python 可以高效地实现这一需求,以下介绍四种常见的方法。
方法一:使用 pandas 库
pandas 是 Python 中强大的数据处理库。遍历文件夹和子文件夹获取所有 Excel 文件路径,然后依次读取每个文件的所有 Sheet 数据,使用 concat 函数进行合并。
import pandas as pd
import os
def merge_excels_pandas(folder_path):
file_paths = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.xlsx'):
file_paths.append(os.path.join(root, file))
data_frames = []
for file_path in file_paths:
excel_file = pd.ExcelFile(file_path)
for sheet_name in excel_file.sheet_names:
data_frames.append(pd.read_excel(file_path, sheet_name=sheet_name))
merged_data = pd.concat(data_frames)
return merged_data
方法二:结合 openpyxl 库
openpyxl 库专门用于处理 Excel 文件。通过类似的文件路径遍历,读取每个 Sheet 的数据并合并。
import openpyxl
import os
def merge_excels_openpyxl(folder_path):
data = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.xlsx'):
file_path = os.path.join(root, file)
workbook = openpyxl.load_workbook(file_path)
for sheet_name in workbook.sheetnames:
sheet = workbook[sheet_name]
rows = sheet.rows
sheet_data = [[cell.value for cell in row] for row in rows]
data.extend(sheet_data)
return data
方法三:利用 xlrd 库
xlrd 也是处理 Excel 的常用库之一。
import xlrd
import os
def merge_excels_xlrd(folder_path):
data = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.xls') or file.endswith('.xlsx'):
file_path = os.path.join(root, file)
workbook = xlrd.open_workbook(file_path)
for sheet_index in range(workbook.nsheets):
sheet = workbook.sheet_by_index(sheet_index)
rows = sheet.get_rows()
sheet_data = [[cell.value for cell in row] for row in rows]
data.extend(sheet_data)
return data
方法四:使用 win32com 库(适用于 Windows 系统)
对于 Windows 环境,win32com 库可以提供更直接的 Excel 操作。
import win32com.client
import os
def merge_excels_win32com(folder_path):
excel_app = win32com.client.Dispatch("Excel.Application")
data = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.xlsx'):
file_path = os.path.join(root, file)
workbook = excel_app.Workbooks.Open(file_path)
for sheet in workbook.Sheets:
rows = sheet.UsedRange.Rows
sheet_data = [[cell.Value for cell in row] for row in rows]
data.extend(sheet_data)
workbook.Close(False)
excel_app.Quit()
return data
以上四种方法各有特点,可以根据实际需求和环境选择合适的方法来批量合并 Excel 文件的 Sheet 数据,提高数据处理的效率。
- 智能城市中Redis的应用探索
- Redis 分布式消息发布与订阅的实现方法
- Redis:打造高可用性数据库系统的核心技术
- 实时推荐系统中Redis的运用
- Redis:打造高性能搜索引擎的得力工具
- Redis:助力高效处理用户行为数据的强大工具
- 物联网系统中Redis的作用与应用实例
- Redis实现分布式缓存功能的方法
- Redis:大规模实时事件高效存储的得力神器
- 基于Redis达成分布式缓存预热
- 大数据处理中Redis的作用与应用场景
- Redis:高速缓存技术的极致典范
- 高并发场景下 Redis 的数据存储解决方案
- Redis助力分布式地理位置查询的实现方法
- Redis助力实现分布式缓存穿透应对方案