用python读取文件夹下所有excel文件中sheet_name=“功能点拆分表”的工作簿,需要保留”子过程描述“列中单元格的颜色,列为空的单元格向上合并单元格,合并列表生成EXCEL后导出,给出面向对象代码
时间: 2024-03-26 07:36:19 浏览: 64
python 实现读取一个excel多个sheet表并合并的方法
好的,以下是面向对象的 Python 代码:
```python
import os
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
from openpyxl.utils import quote_sheetname
from openpyxl.worksheet.table import Table, TableStyleInfo
class ExcelMerger:
def __init__(self, folder_path, output_path):
self.folder_path = folder_path
self.output_path = output_path
def merge(self):
# 获取所有符合条件的工作簿
workbooks = []
for filename in os.listdir(self.folder_path):
if filename.endswith('.xlsx'):
workbook_path = os.path.join(self.folder_path, filename)
workbook = load_workbook(workbook_path)
if '功能点拆分表' in workbook.sheetnames:
workbooks.append(workbook)
# 合并工作簿
merged_workbook = load_workbook(workbooks[0].template)
for workbook in workbooks:
sheet = workbook['功能点拆分表']
merged_sheet = merged_workbook.create_sheet(title=quote_sheetname(sheet.title))
# 复制表头
for row in sheet.iter_rows(min_row=1, max_row=1):
merged_sheet.append([cell.value for cell in row])
# 复制数据
merged_row_index = 2
for row in sheet.iter_rows(min_row=2):
merged_row = []
for cell in row:
if cell.column_letter == 'F':
# 保留颜色
merged_row.append(cell)
elif cell.column_letter == 'A' and not cell.value:
# 合并单元格
while merged_row_index > 2 and merged_sheet.cell(row=merged_row_index - 1, column=1).value is None:
merged_row_index -= 1
merged_sheet.merge_cells(start_row=merged_row_index, end_row=row[0].row, start_column=1, end_column=1)
else:
merged_row.append(cell.value)
merged_sheet.append(merged_row)
merged_row_index += 1
# 添加表格样式
table = Table(displayName=sheet.title, ref=f'A1:F{merged_row_index - 1}')
style = TableStyleInfo(name='TableStyleLight11', showFirstColumn=False, showLastColumn=False,
showRowStripes=True, showColumnStripes=False)
table.tableStyleInfo = style
merged_sheet.add_table(table)
# 导出合并后的工作簿
merged_workbook.save(self.output_path)
```
使用示例:
```python
merger = ExcelMerger('path/to/folder', 'path/to/output.xlsx')
merger.merge()
```
其中,`folder_path` 为包含要合并的 Excel 文件的文件夹路径,`output_path` 为合并后的 Excel 文件输出路径。执行 `merge()` 方法即可进行合并。
阅读全文