如何编程生成商务OneDrive中Excel文件的可嵌入匿名访问链接
问题
需要通过编程为商务OneDrive账户中的Excel文件生成可嵌入网页的匿名访问链接(无需登录即可查看),但目前遇到以下问题:
- 手动获取的嵌入链接仍触发登录提示,无法满足需求
- 使用R语言Microsoft365R包调用
create_share_link(type='embed')对商务OneDrive无效 - 成功创建的匿名查看共享链接无法直接嵌入网页
相关测试代码如下:
library(Microsoft365R) library(openxlsx) # 成功连接商务OneDrive odb <- get_business_onedrive() # 成功上传测试文件 odb$upload_file( src = "data/iris.xlsx", dest = "public/iris.xlsx" ) # 成功列出目标文件夹下的文件 files <- odb$list_files( path = "public" ) # 获取目标文件对象 file <- odb$get_item( itemid = files$id[1] ) # 创建的匿名查看链接无法嵌入 file$create_share_link( type = "view", expiry = NULL, scope = "anonymous" ) # 调用embed类型的共享链接创建失败,商务OneDrive账户不支持该参数 file$create_share_link( type = "embed", expiry = NULL ) # 成功打开文件(仅当前登录用户可见) obd$open_item( itemid = files$id[1] )
解决方案
商务OneDrive的嵌入链接需要同时满足匿名权限和嵌入权限配置,Microsoft365R的create_share_link方法暂不支持直接生成商务账号的嵌入链接,可通过直接调用Azure Graph API实现:
步骤1:获取文件的匿名查看共享链接
先创建匿名查看权限的共享链接,提取其核心参数:
# 创建匿名查看链接并保存关键信息 share_link <- file$create_share_link(type = "view", scope = "anonymous") share_id <- share_link$shareId
步骤2:调用Graph API生成可嵌入的匿名链接
通过Microsoft365R封装的Graph API调用方法,为共享链接添加嵌入权限:
# 构造Graph API请求路径,对shareId进行URL编码 encoded_share_id <- URLencode(share_id, reserved = TRUE) graph_endpoint <- sprintf("/shares/%s/permission", encoded_share_id) # 构造请求体,授予Office Online应用匿名读取权限 request_body <- list( roles = c("read"), grantedToIdentities = list( list( application = list( id = "00000003-0000-0ff1-ce00-000000000000", # 官方Office Online应用ID displayName = "Office Online" ) ) ), link = list( type = "embed", scope = "anonymous" ) ) # 发送POST请求获取嵌入链接 embed_result <- odb$call_graph_endpoint(graph_endpoint, method = "POST", body = request_body) embed_url <- embed_result$link$webUrl
步骤3:用于网页嵌入
拿到embed_url后,可直接用iframe标签嵌入网页:
<iframe src="%s" width="100%" height="600px" frameborder="0"></iframe>
批量处理说明
将上述步骤放入循环中,遍历目标文件夹下的所有文件即可实现批量生成:
# 遍历public文件夹下的所有文件批量生成嵌入链接 files <- odb$list_files(path = "public") embed_links <- c() for (i in seq(nrow(files))) { file <- odb$get_item(itemid = files$id[i]) # 创建匿名查看链接 share_link <- file$create_share_link(type = "view", scope = "anonymous") # 生成嵌入链接 encoded_share_id <- URLencode(share_link$shareId, reserved = TRUE) graph_endpoint <- sprintf("/shares/%s/permission", encoded_share_id) request_body <- list( roles = c("read"), grantedToIdentities = list( list( application = list( id = "00000003-0000-0ff1-ce00-000000000000", displayName = "Office Online" ) ) ), link = list( type = "embed", scope = "anonymous" ) ) embed_result <- odb$call_graph_endpoint(graph_endpoint, method = "POST", body = request_body) embed_links <- c(embed_links, embed_result$link$webUrl) } # 输出所有嵌入链接 print(embed_links)
内容的提问来源于stack exchange,提问作者S3AN556
相关产品推荐
相关产品推荐

