在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
相关产品推荐
相关产品推荐

