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

如何使用Python openpyxl遍历Excel指定列的所有行单元格

修改点说明

  • 修复原代码中bok/book变量名不一致的报错问题
  • 新增A列遍历逻辑,自动跳过空单元格
  • 新增异常判断,避免单元格内容无冒号时程序崩溃
  • 调整写入行逻辑,每个A列单元格的拆分结果单独占一行,不会互相覆盖

完整修改后代码

import openpyxl

# 加载工作簿,统一变量名
book = openpyxl.load_workbook('C:/Users/zalka/Desktop/Python project/new13.xlsx')
sheet = book.active
Column_base = 3

# 遍历A列所有有内容的单元格,可自行调整min_row参数跳过表头
for row_idx, cell in enumerate(sheet.iter_rows(min_col=1, max_col=1, min_row=1, values_only=False), start=1):
    current_cell = cell[0]
    # 跳过空单元格
    if not current_cell.value:
        continue
    tech_details = str(current_cell.value).splitlines()
    i = 0
    for tech_detail in tech_details:
        # 跳过没有冒号的行,避免报错
        if ":" not in tech_detail:
            continue
        s = tech_detail.index(":")
        name = tech_detail[:s].strip()
        value = tech_detail[s+1:].strip()
        # 列名统一写在第3行,每个单元格的拆分值写在对应行
        sheet.cell(row=3, column=i+Column_base).value = name
        sheet.cell(row=row_idx, column=i+Column_base).value = value
        i += 1

book.save('C:/Users/zalka/Desktop/Python project/write2cell2.xlsx')

可选调整项

  • 如果A列有表头不需要处理,修改iter_rows的min_row参数即可,比如表头占2行就设min_row=3
  • 如果不需要统一把列名放在第3行,可以自行调整row=3的写入逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:24:01