python合并同一文件夹下所有excel表格
时间: 2023-11-08 12:14:04 浏览: 44
可以使用Python中的pandas库来实现合并同一文件夹下所有excel表格的功能。具体步骤如下:
1. 导入pandas库
```python
import pandas as pd
```
2. 使用pandas的read_excel函数读取每个excel文件,并将其存储到一个列表中
```python
import os
# 获取文件夹中所有的excel文件
folder_path = "path/to/folder"
all_files = os.listdir(folder_path)
excel_files = [f for f in all_files if f.endswith('.xlsx') or f.endswith('.xls')]
# 读取每个excel文件,并将其存储到一个列表中
data_frames = []
for file in excel_files:
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path)
data_frames.append(df)
```
3. 使用pandas的concat函数将所有数据框合并为一个
```python
# 使用concat函数将所有数据框合并为一个
merged_df = pd.concat(data_frames, ignore_index=True)
```
4. 将合并后的数据框保存为一个新的excel文件
```python
# 将合并后的数据框保存为一个新的excel文件
merged_df.to_excel("path/to/output_file.xlsx", index=False)
```
完整代码如下:
```python
import pandas as pd
import os
# 获取文件夹中所有的excel文件
folder_path = "path/to/folder"
all_files = os.listdir(folder_path)
excel_files = [f for f in all_files if f.endswith('.xlsx') or f.endswith('.xls')]
# 读取每个excel文件,并将其存储到一个列表中
data_frames = []
for file in excel_files:
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path)
data_frames.append(df)
# 使用concat函数将所有数据框合并为一个
merged_df = pd.concat(data_frames, ignore_index=True)
# 将合并后的数据框保存为一个新的excel文件
merged_df.to_excel("path/to/output_file.xlsx", index=False)
```