码修
1 小时前
pandas 是为 Python 编程语言编写的用于数据处理和分析的软件库. 合并同一目录下的多个 Excel 文件是办公中经常遇到的场景, 本文将利用 pandas 完成该操作.
1 引入作案工具(pandas 和 路径工具)
- import pandas as pd
- from pathlib import Path
2 传入 Excel 所在目录
excel_dir = Path('excel 目录, 如: E:/excel_files')
3 获取到路径下面的 Excel 文件列表
excel_files = excel_dir.glob('*.xlsx')
4 创建 pandas 表格类型 dataFrame
df = pd.DataFrame()
5 遍历 Excel 文件, 读到数据添加到 pandas 表格中
- for xls in excel_files:
- data = pd.read_excel(xls, 'sheet_name')
- df = df.append(data)
6 将 pandas 表格中所有数据 (合并后的 Excel 数据) 写入到新的 Excel 中
df.to_excel(excel_dir / "output.xlsx")
参考资料
- Import multiple Excel files into python pandas and concatenate them into one dataframe - Stack Overflow
- Combining Data From Multiple Excel Files - Practical Business Python https://pbpython.com/excel-file-combine.html
来源: http://www.mzh.ren/excel-file-combined-by-pandas.html