openpyxl 合并多个xlsx
时间: 2023-09-13 16:07:56 浏览: 78
文件
要合并多个xlsx文件,可以使用openpyxl库和Python编程语言。下面是一些基本步骤:
1. 导入openpyxl库和其他必要的库(例如os)
```python
import openpyxl
import os
```
2. 创建一个新的工作簿(或选择现有的工作簿)并定义要合并的文件夹路径
```python
merged_workbook = openpyxl.Workbook()
folder_path = 'C:/path/to/folder'
```
3. 使用os库列出文件夹中所有的xlsx文件,并循环遍历每个文件
```python
for filename in os.listdir(folder_path):
if filename.endswith('.xlsx'):
# 读取单个工作簿
workbook = openpyxl.load_workbook(os.path.join(folder_path, filename))
# 循环遍历每个工作表
for sheetname in workbook.sheetnames:
worksheet = workbook[sheetname]
# 循环遍历每个单元格
for row in worksheet.iter_rows():
for cell in row:
# 将单元格的值复制到新的工作簿中
merged_workbook[sheetname][cell.coordinate].value = cell.value
```
4. 保存合并后的工作簿
```python
merged_workbook.save('merged_file.xlsx')
```
完整代码如下:
```python
import openpyxl
import os
merged_workbook = openpyxl.Workbook()
folder_path = 'C:/path/to/folder'
for filename in os.listdir(folder_path):
if filename.endswith('.xlsx'):
# 读取单个工作簿
workbook = openpyxl.load_workbook(os.path.join(folder_path, filename))
# 循环遍历每个工作表
for sheetname in workbook.sheetnames:
worksheet = workbook[sheetname]
# 循环遍历每个单元格
for row in worksheet.iter_rows():
for cell in row:
# 将单元格的值复制到新的工作簿中
merged_workbook[sheetname][cell.coordinate].value = cell.value
merged_workbook.save('merged_file.xlsx')
```
阅读全文