python合并多个excel表格
时间: 2023-09-16 15:14:06 浏览: 170
要合并多个Excel表格,可以使用Python的pandas库。以下是合并多个Excel表格的步骤:
步骤1:导入必要的库
```python
import pandas as pd
import glob
```
步骤2:使用glob库获取所有Excel文件的文件名
```python
path = r'path/to/files' # 文件所在的路径
all_files = glob.glob(path + "/*.xlsx") # 获取所有xlsx文件的文件名
```
步骤3:使用pandas库将所有Excel文件读取到一个DataFrame中
```python
li = []
for filename in all_files:
df = pd.read_excel(filename, index_col=None, header=0)
li.append(df)
df_combined = pd.concat(li, axis=0, ignore_index=True)
```
这个代码块将所有Excel文件读取到一个名为`df_combined`的DataFrame中,并将它们按照行的顺序合并。
步骤4:将合并后的DataFrame保存为一个新的Excel文件
```python
df_combined.to_excel("path/to/output_file.xlsx", index=False)
```
这个代码块将合并后的DataFrame保存为一个新的Excel文件。
完整代码示例:
```python
import pandas as pd
import glob
path = r'path/to/files' # 文件所在的路径
all_files = glob.glob(path + "/*.xlsx") # 获取所有xlsx文件的文件名
li = []
for filename in all_files:
df = pd.read_excel(filename, index_col=None, header=0)
li.append(df)
df_combined = pd.concat(li, axis=0, ignore_index=True)
df_combined.to_excel("path/to/output_file.xlsx", index=False)
```
阅读全文
相关推荐








