python將多個工作薄合并為一個工作薄多表
时间: 2023-07-01 16:12:59 浏览: 92
你可以使用Python中的pandas库来合并多个工作簿。下面是一个示例代码,可以将多个Excel文件合并为一个工作簿中的多个表:
```python
import pandas as pd
import glob
# 读取所有Excel文件
all_files = glob.glob("*.xlsx")
# 创建一个空的DataFrame
df = pd.DataFrame()
# 循环遍历所有文件,并将它们合并到DataFrame中
for filename in all_files:
# 读取Excel文件中的所有表
xl = pd.ExcelFile(filename)
for sheet_name in xl.sheet_names:
# 将表中的数据添加到DataFrame中
sheet_data = xl.parse(sheet_name)
df = df.append(sheet_data)
# 将所有表写入一个新的Excel文件中
with pd.ExcelWriter("merged.xlsx") as writer:
for sheet_name, sheet_data in df.groupby("Sheet_Name"):
sheet_data.to_excel(writer, sheet_name=sheet_name, index=False)
```
在这个示例代码中,我们使用了glob模块来获取当前目录中的所有Excel文件,然后使用pandas的ExcelFile方法读取每个文件中的所有表,并将它们添加到一个空的DataFrame中。最后,我们使用ExcelWriter方法将DataFrame中的所有表写入一个新的Excel文件中。
阅读全文
相关推荐


















