技术文摘
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 数据,提高数据处理的效率。
- MySQL 存储过程中怎样实现调用多个过程
- 如何在数据集上运用 MySQL UNION 运算符
- 如何创建在指定时间段执行且在另一指定时间段结束的MySQL重复事件
- 在 MySQL 语句中同时使用 G 和分号 (;) 终止符号会怎样
- 存储过程中怎样使用预编译语句
- 连接MongoDB与NodeJS
- 怎样对 MySQL 表中存储的日期运用 EXTRACT() 函数
- 编写MySQL语句时c选项的作用
- MySQL LEFT JOIN 是什么以及如何编写相关查询
- MySQL 怎样获取日期的部分内容
- 在MySQL里创建一个与另一表匹配的表
- 数据库是什么及使用 MySQL 数据库的优点有哪些
- 在 MySQL 中如何利用 RAND() 函数在 ORDER BY 子句里打乱行集
- 在DATEDIFF()函数参数中包含时间与日期组件时MySQL的返回值
- MySQL 中怎样获取当月第一天