以下是一个示例代码,可以实现从 Excel 工作表中提取相同表头内容的行,并将其复制到新的工作表中,同时保留原始格式。该代码还将冻结第一个工作表中 A1 列的内容并将其复制到每个新的工作表中。

import openpyxl

# 打开 Excel 文件
wb = openpyxl.load_workbook('example.xlsx')

# 获取所有工作表
sheets = wb.sheetnames

# 冻结第一个工作表窗格 A1 列的内容
ws1 = wb[sheets[0]]
ws1.freeze_panes = 'B2'

# 遍历每个工作表
for sheet_name in sheets:
    # 创建新的工作表
    new_ws = wb.create_sheet(title=sheet_name)
    
    # 获取当前工作表
    ws = wb[sheet_name]
    
    # 获取表头列
    header_col = None
    for col in ws.iter_cols(min_row=1, max_row=1):
        if col[0].value == '表头':
            header_col = col
            break
    
    # 如果没有找到表头列,则跳过当前工作表
    if header_col is None:
        continue
    
    # 遍历表头列中所有相同内容的行,并复制到新的工作表中
    for cell in header_col:
        if cell.row == 1:
            continue
        value = cell.value
        rows = [cell.row]
        for row in range(cell.row+1, ws.max_row+1):
            if ws.cell(row=row, column=cell.column).value == value:
                rows.append(row)
            else:
                break
        new_rows = new_ws.copy_rows(rows=rows, start_row=1, end_row=len(rows))
        
        # 复制窗格 A1 的内容到新的工作表
        new_ws.cell(row=1, column=1).value = ws1.cell(row=1, column=1).value
        new_ws.cell(row=1, column=1)._style = ws1.cell(row=1, column=1)._style
        
        # 复制表头列到新的工作表
        for i, row in enumerate(new_rows):
            row[0].value = value
            row[0]._style = cell._style

需要注意的是,上述代码中用到了 openpyxl 库,需要先安装该库才能运行。可以使用以下命令安装:

pip install openpyxl

原文地址: https://www.cveoy.top/t/topic/fW6U 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录