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

如何在React/NodeJS中认证并获取SharePoint上的XLSX文件

解决SharePoint认证并访问XLSX文件的方案

React 端实现(基于@pnp/sp + MSAL)

1. 前置准备

  • 在Azure AD注册单页应用(SPA),获取clientId,添加SharePoint权限(如Sites.Read.All),设置重定向URI为你的React应用地址。
  • 安装依赖:
npm install @pnp/sp @azure/msal-react @azure/msal-browser

2. 初始化MSAL和PnP SP

在应用入口文件(如index.js)配置实例:

import { PublicClientApplication } from "@azure/msal-browser";
import { MsalProvider } from "@azure/msal-react";
import { sp } from "@pnp/sp";

const msalConfig = {
  auth: {
    clientId: "你的Azure AD应用clientId",
    authority: "https://login.microsoftonline.com/你的租户ID",
    redirectUri: "你的React应用地址(比如http://localhost:3000)",
  },
};

const pca = new PublicClientApplication(msalConfig);

// 关联MSAL的token获取逻辑,初始化PnP SP
sp.setup({
  sp: {
    baseUrl: "https://[ORGANIZATION_NAME].sharepoint.com/teams/[ORGANIZATION_TEAM_NAME]",
    fetchClientFactory: () => {
      return async (url, options) => {
        const tokenRequest = {
          scopes: ["https://[ORGANIZATION_NAME].sharepoint.com/.default"],
        };
        const response = await pca.acquireTokenSilent(tokenRequest);
        options.headers.set("Authorization", `Bearer ${response.accessToken}`);
        return fetch(url, options);
      };
    },
  },
});

// 用MsalProvider包裹应用
ReactDOM.render(
  <MsalProvider instance={pca}>
    <App />
  </MsalProvider>,
  document.getElementById("root")
);

3. 登录并读取XLSX文件

在业务组件中实现操作逻辑:

import { useMsal } from "@azure/msal-react";
import { sp } from "@pnp/sp";
import * as XLSX from "xlsx";

const ExcelReader = () => {
  const { instance, accounts } = useMsal();

  const login = async () => {
    await instance.loginPopup({
      scopes: ["https://[ORGANIZATION_NAME].sharepoint.com/Sites.Read.All"],
    });
  };

  const fetchExcelData = async () => {
    if (!accounts.length) {
      alert("请先登录");
      return;
    }
    // 获取文件二进制内容
    const fileBuffer = await sp.web.getFileByServerRelativeUrl("/teams/[ORGANIZATION_TEAM_NAME]/[文档库相对路径]/[FILENAME].xlsx").getBuffer();
    // 解析Excel为JSON
    const workbook = XLSX.read(new Uint8Array(fileBuffer), { type: "array" });
    const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
    const jsonData = XLSX.utils.sheet_to_json(firstSheet);
    // 后续可将jsonData上传至数据库
    console.log(jsonData);
  };

  return (
    <div>
      <button onClick={login}>登录SharePoint</button>
      <button onClick={fetchExcelData}>获取Excel数据</button>
    </div>
  );
};

export default ExcelReader;

NodeJS 端实现(基于@pnp/nodejs)

1. 前置准备

  • 在Azure AD注册非SPA应用,获取clientId、clientSecret、tenantId,添加应用权限(如Sites.Read.All)并获取管理员同意。
  • 安装依赖:
npm install @pnp/nodejs @pnp/sp xlsx

2. 初始化PnP并读取文件

创建脚本文件(如fetch-sp-excel.js):

import { sp } from "@pnp/sp";
import { SPFetchClient } from "@pnp/nodejs";
import * as XLSX from "xlsx";

// 配置认证参数
const siteUrl = "https://[ORGANIZATION_NAME].sharepoint.com/teams/[ORGANIZATION_TEAM_NAME]";
const clientId = "你的Azure AD应用clientId";
const clientSecret = "你的Azure AD应用clientSecret";
const tenantId = "你的租户ID";

// 初始化PnP SP
sp.setup({
  sp: {
    baseUrl: siteUrl,
    fetchClientFactory: () => {
      return new SPFetchClient(siteUrl, clientId, clientSecret, tenantId);
    },
  },
});

// 读取并解析Excel文件
const fetchAndParseExcel = async () => {
  try {
    // 文件的服务器相对路径,示例:"/teams/[ORGANIZATION_TEAM_NAME]/Documents/[FILENAME].xlsx"
    const fileBuffer = await sp.web.getFileByServerRelativeUrl("/teams/[ORGANIZATION_TEAM_NAME]/[文档库路径]/[FILENAME].xlsx").getBuffer();
    const workbook = XLSX.read(new Uint8Array(fileBuffer), { type: "array" });
    const sheetData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
    // 替换为你的数据库上传逻辑
    console.log("解析后的Excel数据:", sheetData);
  } catch (error) {
    console.error("获取文件失败:", error);
  }
};

fetchAndParseExcel();

注意事项

  • 替换代码中所有[ORGANIZATION_NAME]、[ORGANIZATION_TEAM_NAME]、[FILENAME]、[文档库路径]为实际值。
  • 权限配置按需选择:仅读取文件用Sites.Read.All即可,如需修改则用Sites.ReadWrite.All,也可配置文档库级别的精细权限。
  • Postman测试时,可通过Azure AD获取access token后,在请求头添加Authorization: Bearer {token}验证认证有效性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:35:15