You need to enable JavaScript to run this app. 如何使用Office.js的getFileAsync方法获取SharePoint存储的docx格式Word文档
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Office.js的getFileAsync方法获取SharePoint存储的docx格式Word文档

结论

调用Office.context.document.getFileAsync方法可以直接获取到.docx格式的Word文件,只需指定对应的文件类型参数即可,无需额外做格式转换。

具体实现步骤

  • 调用getFileAsync时传入Office.FileType.Compressed枚举值,该值对应返回的就是标准docx格式的二进制压缩内容,和直接从SharePoint下载的docx文件格式完全一致
  • 分块读取完整文件内容,Office.js默认按4MB大小分块返回,避免大文件读取时内存溢出
  • 将所有二进制块拼接为Blob对象,指定docx对应的标准MIME类型
  • 封装进FormData后即可向第三方API发起POST上传请求

完整代码示例

// 调用getFileAsync获取docx格式文件
Office.context.document.getFileAsync(Office.FileType.Compressed, { sliceSize: 4194304 /* 4MB */ }, function (result) {
    if (result.status === Office.AsyncResultStatus.Succeeded) {
        const file = result.value;
        const allSlices = [];
        let sliceCount = 0;

        // 递归读取所有分块
        function getNextSlice() {
            file.getSliceAsync(sliceCount, function (sliceResult) {
                if (sliceResult.status === Office.AsyncResultStatus.Succeeded) {
                    // 将当前块的Uint8Array存入数组
                    allSlices.push(new Uint8Array(sliceResult.value.data));
                    sliceCount++;
                    if (sliceCount < file.sliceCount) {
                        getNextSlice();
                    } else {
                        // 所有块读取完成,拼接为Blob
                        const docxBlob = new Blob(allSlices, {
                            type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                        });
                        // 封装FormData上传,指定文件名带.docx后缀
                        const formData = new FormData();
                        formData.append("uploadFile", docxBlob, "document.docx");
                        
                        // 发起POST请求
                        fetch("第三方API实际地址", {
                            method: "POST",
                            body: formData
                        }).then(response => {
                            // 自定义响应处理逻辑
                            console.log("上传完成");
                        }).catch(err => {
                            console.error("上传失败", err);
                        });
                        // 关闭文件句柄释放内存
                        file.closeAsync();
                    }
                } else {
                    console.error("读取文件块失败", sliceResult.error);
                    file.closeAsync();
                }
            });
        }
        getNextSlice();
    } else {
        console.error("获取文件失败", result.error);
    }
});

注意事项

  • 插件清单(manifest.xml)中需要配置ReadDocument或更高权限,否则调用getFileAsync会被拦截
  • 该方法读取的是当前用户打开的文档最新内容,不管文档存储在SharePoint还是本地,都可以正常获取,不需要单独调用SharePoint接口下载文件
  • 如果第三方接口有文件大小限制,可自行调整sliceSize参数的数值,最小支持1KB,无硬性上限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 13:45:02