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

如何用Python在Excel中写入STOCKHISTORY数组函数并正常生效

解决openpyxl写入Excel STOCKHISTORY数组函数自动添加@的问题

问题根源

直接通过ws['A1'] = 公式赋值时,openpyxl会将其标记为普通单元格公式。而STOCKHISTORY是动态数组函数,Excel默认会对普通公式中的动态数组函数添加@运算符(隐式交集),强制只返回单个结果,导致无法自动溢出填充列数据。

单个股票的修复代码

使用openpyxl的array_formula属性明确指定这是数组公式,避免Excel添加@:

from openpyxl import Workbook

wb = Workbook()
ws = wb.active

stocks = ["AAPL"]

# 用array_formula替代直接赋值,无需手动添加大括号或@
ws['A1'].array_formula = f"STOCKHISTORY(\"{stocks[0]}\",\"1/1/20\",\"1/1/24\",2,1,1)"

wb.save("C:/Users/there/Desktop/TEST.xlsx")

批量处理多股票的扩展方案

如果要给多个股票代码批量生成数组公式,需为每个公式预留足够的溢出空间(避免结果重叠),示例代码如下:

from openpyxl import Workbook

wb = Workbook()
ws = wb.active

stocks = ["AAPL", "MSFT", "GOOGL"]
current_col = 1  # 从A列开始

for stock in stocks:
    target_cell = ws.cell(row=1, column=current_col)
    target_cell.array_formula = f"STOCKHISTORY(\"{stock}\",\"1/1/20\",\"1/1/24\",2,1,1)"
    current_col += 3  # 间隔2列,防止不同股票的溢出数据互相覆盖

wb.save("C:/Users/there/Desktop/MULTI_STOCKS.xlsx")

验证效果

打开生成的Excel文件后,STOCKHISTORY的结果会自动溢出到目标单元格下方的行和右侧的列,完整展示日期、收盘价等数据,不会仅显示单个"Close"值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 02:35:02