如何使用python的openpyxl库 将多个excel合并到一个excel里的一个sheet页上并保持样式不变
时间: 2023-11-28 18:51:21 浏览: 114
你可以按照以下步骤使用openpyxl库将多个excel合并到一个excel里的一个sheet页上并保持样式不变:
1. 导入openpyxl库
```
import openpyxl
```
2. 创建一个新的工作簿,并指定要合并的sheet页名称
```
new_workbook = openpyxl.Workbook()
new_sheet = new_workbook.active
new_sheet.title = "Merged Data"
```
3. 读取要合并的excel文件,并将数据复制到新的sheet页中
```
for file_name in file_list:
workbook = openpyxl.load_workbook(file_name)
sheet = workbook.active
for row in sheet.iter_rows():
new_sheet.append([cell.value for cell in row])
```
4. 复制样式,包括字体、颜色、格式等
```
for file_name in file_list:
workbook = openpyxl.load_workbook(file_name)
sheet = workbook.active
for row in sheet.iter_rows():
new_sheet.append([cell.value for cell in row])
for cell in row:
new_cell = new_sheet.cell(row=cell.row, column=cell.column)
new_cell.font = cell.font
new_cell.fill = cell.fill
new_cell.border = cell.border
new_cell.number_format = cell.number_format
new_cell.alignment = cell.alignment
```
5. 保存新的合并后的excel文件
```
new_workbook.save("merged_data.xlsx")
```
完整代码示例:
```
import openpyxl
file_list = ["file1.xlsx", "file2.xlsx", "file3.xlsx"]
new_workbook = openpyxl.Workbook()
new_sheet = new_workbook.active
new_sheet.title = "Merged Data"
for file_name in file_list:
workbook = openpyxl.load_workbook(file_name)
sheet = workbook.active
for row in sheet.iter_rows():
new_sheet.append([cell.value for cell in row])
for cell in row:
new_cell = new_sheet.cell(row=cell.row, column=cell.column)
new_cell.font = cell.font
new_cell.fill = cell.fill
new_cell.border = cell.border
new_cell.number_format = cell.number_format
new_cell.alignment = cell.alignment
new_workbook.save("merged_data.xlsx")
```
阅读全文