openpyxl 多个sheet文件生成一个xlsx
时间: 2024-05-05 14:17:19 浏览: 203
可以使用openpyxl库中的Workbook和load_workbook方法来实现多个sheet文件生成一个xlsx文件。
1. 创建一个Workbook对象
```python
from openpyxl import Workbook
wb = Workbook()
```
2. 加载多个sheet文件
```python
from openpyxl import load_workbook
wb2 = load_workbook(filename='file1.xlsx')
wb3 = load_workbook(filename='file2.xlsx')
```
3. 将每个文件的sheet复制到Workbook对象中
```python
for sheet in wb2:
new_sheet = wb.create_sheet(title=sheet.title)
for row in sheet.iter_rows():
values = [cell.value for cell in row]
new_sheet.append(values)
for sheet in wb3:
new_sheet = wb.create_sheet(title=sheet.title)
for row in sheet.iter_rows():
values = [cell.value for cell in row]
new_sheet.append(values)
```
4. 保存Workbook对象为xlsx文件
```python
wb.save('output.xlsx')
```
完整代码示例:
```python
from openpyxl import Workbook, load_workbook
# 创建一个Workbook对象
wb = Workbook()
# 加载多个sheet文件
wb2 = load_workbook(filename='file1.xlsx')
wb3 = load_workbook(filename='file2.xlsx')
# 将每个文件的sheet复制到Workbook对象中
for sheet in wb2:
new_sheet = wb.create_sheet(title=sheet.title)
for row in sheet.iter_rows():
values = [cell.value for cell in row]
new_sheet.append(values)
for sheet in wb3:
new_sheet = wb.create_sheet(title=sheet.title)
for row in sheet.iter_rows():
values = [cell.value for cell in row]
new_sheet.append(values)
# 保存Workbook对象为xlsx文件
wb.save('output.xlsx')
```
阅读全文