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

Python如何根据Excel列标题值确定df.to_excel的写入起始列

实现方案

你需要先读取目标工作表的首行表头,匹配你要写入的首个周值对应的列索引,直接赋值给startcol参数即可,完整实现逻辑如下:

步骤1:读取目标工作表的表头获取列索引

推荐用openpyxl作为写入引擎(也是xlsx文件的常用默认引擎),可以直接从writer对象里读取对应工作表的首行值:

import pandas as pd

# 前置定义:你要写入的周序列,对应你原来的Weeknum、Weeknum1、Weeknum2
write_weeks = ['Week 14', 'Week 15', 'Week 16']
target_sheet_name = 'QTY SLS'

# 你的writer初始化代码,保持原有写法即可,注意开启追加写入模式
writer = pd.ExcelWriter('你的目标Excel文件路径.xlsx', engine='openpyxl', mode='a', if_sheet_exists='overlay')

# 核心逻辑:匹配起始列索引
if target_sheet_name in writer.book.sheetnames:
    ws = writer.book[target_sheet_name]
    # 读取首行表头的值,默认表头在Excel第1行,对应索引1,若你的表头在其他行修改数字即可
    header_row = [cell.value for cell in ws[1]]
    # 取写入序列的第一个周值匹配列位置,注意pandas的startcol从0开始,直接取列表索引即可
    first_week = write_weeks[0]
    start_col = header_row.index(first_week) if first_week in header_row else 8
else:
    # 工作表不存在的兜底逻辑,可自行调整
    start_col = 8

步骤2:修改写入参数

替换你原有to_excel方法的startcol参数即可:

df.to_excel(writer, 
            columns = write_weeks, 
            sheet_name = target_sheet_name, 
            startrow = 5, 
            startcol = start_col, 
            header = False, 
            index = False)

# 保存文件
writer.close()

注意事项

  • 如果你的表头不在Excel的第1行,修改ws[1]里的数字即可,比如表头在第2行就改成ws[2]
  • 如果你用的是xlsxwriter作为引擎,读取表头的逻辑略有差异,openpyxl是目前最通用的适配方案
  • 如果输入的周序列是倒序比如['Week 16', 'Week 15', 'Week 14'],会自动匹配第一个元素的位置作为写入起始列,后续列依次往后写,和你的输入顺序完全对应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 05:36:05