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

在Excel Office Script中调用SharePoint List REST API遇权限问题求助

问题

需要在网页版Excel中通过Office Script实现对SharePoint列表的读写操作,将Excel作为支持智能计算的表单(因公司限制无法使用Power Apps/Power Automate)。当前使用的脚本如下:

let bob = await getListData();
let mySheet = workbook.getActiveWorksheet();
let myCell = mySheet.getCell(1,1)
myCell.setValue(bob)

}

async function getListData(){
 let dataj='test';
 let headers:{};
 headers ={
   "method":"GET",
   "credentials": "same-origin", 
   "headers": {
     "accept": "application/json;odata=verbose",
     "accept-language": "en-US,en;q=0.9",
     "content-type": "application/json;odata=verbose"}
 }
 await fetch("https://mySite.sharepoint.com/sites/myGroup/_api/web/lists/GetByTitle('myList')/items", headers)
 .then((data) => {dataj=data.statusText; console.log(dataj)});
 return dataj
}

已在浏览器控制台测试getListData函数并得到预期响应,但在Office Script中:

  • 使用credentials: "same-origin"时返回"forbidden"
  • 改为credentials: "include"时返回"failed to fetch"
解决思路
  • 移除Credentials配置:Office Script运行在Office沙箱环境中,无需手动设置credentials参数。浏览器的同源策略规则不适用于Office Script的fetch调用,手动配置反而会触发权限校验问题,直接删除该配置项即可。
  • 精简请求头:GET请求不需要content-type头,多余的请求头可能引发校验失败。仅保留accept: "application/json;odata=verbose"即可,其他非必要头可移除。
  • 修正响应处理逻辑:当前脚本仅返回状态文本,需解析响应的JSON数据。修改后的fetch处理逻辑示例:
    await fetch("https://mySite.sharepoint.com/sites/myGroup/_api/web/lists/GetByTitle('myList')/items", {
      method: "GET",
      headers: { "accept": "application/json;odata=verbose" }
    })
    .then(response => {
      if (!response.ok) throw new Error(response.statusText);
      return response.json();
    })
    .then(data => {
      dataj = JSON.stringify(data.d.results); // 提取列表项数据
      console.log(dataj);
    })
    .catch(err => console.error(err));
    
  • 验证权限与租户一致性:确保当前登录账号对目标SharePoint列表有读取权限,且Excel文件所在站点与列表站点属于同一租户(跨租户调用会被限制)。
  • 优先使用Office Script内置SharePoint API:Office Script提供了专门的SharePoint命名空间,无需手动处理请求头,调用更稳定。示例代码:
    async function getListData() {
      const siteUrl = "https://mySite.sharepoint.com/sites/myGroup";
      const listTitle = "myList";
      const items = await SharePoint.listItems.getListItems(siteUrl, listTitle);
      return JSON.stringify(items);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:20:30