You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用openpyxl复制B列含"move"值的行至新Excel表格?

使用openpyxl筛选并复制指定行到新Excel表格

以下是实现需求的完整代码,逻辑为读取源Excel文件,筛选出B列包含"move"的行并复制到新Excel文件:

from openpyxl import load_workbook, Workbook

# 替换为你的源文件和目标文件路径
source_file = "source.xlsx"
target_file = "target.xlsx"

# 加载源工作簿与工作表
source_wb = load_workbook(source_file)
source_ws = source_wb.active  # 若需指定工作表,可改为source_wb["Sheet名称"]

# 创建目标工作簿与工作表
target_wb = Workbook()
target_ws = target_wb.active

# 复制表头(不需要表头可删除这段,同时修改下方遍历的min_row为1)
header_row = next(source_ws.iter_rows(values_only=True))
target_ws.append(header_row)

# 遍历源表行,筛选B列含"move"的行
for row in source_ws.iter_rows(min_row=2, values_only=True):
    # 兼容单元格为空的情况,不区分大小写匹配"move"
    if row[1] and "move" in str(row[1]).lower():
        target_ws.append(row)

# 保存并关闭工作簿
target_wb.save(target_file)
source_wb.close()
target_wb.close()

补充说明:

  • 若需精确区分大小写,去掉代码中的.lower()即可
  • 如果需要保留单元格格式(字体、填充色等),不要用values_only=True,改为逐个复制单元格属性,示例片段:
# 替换上方的遍历代码,实现带格式复制
for src_row_idx, row in enumerate(source_ws.iter_rows(min_row=1), 1):
    cell_b = row[1]
    if cell_b.value and "move" in str(cell_b.value).lower():
        for col_idx, cell in enumerate(row, 1):
            target_cell = target_ws.cell(row=src_row_idx, column=col_idx)
            target_cell.value = cell.value
            target_cell.font = cell.font.copy()
            target_cell.fill = cell.fill.copy()
            # 可按需添加边框、对齐方式等格式复制

内容的提问来源于stack exchange,提问作者irishombian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:01:38