msgraph - 使用 msgraph 服务从 sharepoint 下载 xlsx 文件

msgraph - download xlsx file from sharepoint using msgraph service

我需要从 myFolder 下载所有 xlsx 文件我有两种方法 getExcelSheets 获取所有 excel 工作表列表

然后使用此信息通过调用 getFileContentById 方法使用 @microsoft.graph.downloadUrl 下载文件,但我无法获取并将其转换为 xlsx 格式

import { Client } from "@microsoft/microsoft-graph-client";
import axios from "axios";
import * as MicrosoftGraph from "@microsoft/microsoft-graph-types";

export async function getExcelSheets(
  template_name: string,
  msgraph_client: Client,
): Promise<MicrosoftGraph.DriveItem[]> {
  const result = await msgraph_client
    .api(
      `drives/{driver_id}/root:/myFolder/${template_name}:/children`
    )
    .get();
  return result.value as MicrosoftGraph.DriveItem[];
}

export async function getFileContentById(download_url: string): Promise<any> {
  const response = await axios.get(download_url);
  return response;
}

有关我如何获取文件然后将其转换为 xlsx 的任何提示我正在使用此方法将缓冲区转换为 xlsx

xlsx.read(file, { type: "buffer" })

您在 getFileContentById 中进行的 Axios 调用将接收一个流,您可以将该流写入文件或转换为 xlsx 如下所示,

export async function getFileContentById(download_url: string): Promise<any> {
   const writer = fs.createWriteStream('file.xlsx');
   return axios({
      method: 'get',
      url: download_url,
      responseType: 'stream',
   }).then(response => {
      // Save the file and read later
      response.data.pipe(writer);
      
      // OR Convert the binary to xlsx usibng the library
      const sheet = XLSX.read(response.data, { type: "buffer" });
      console.log(sheet)
      /*
      {
        SheetNames: [ 'Sheet1' ],
        Sheets: { Sheet1: { A1: [Object], '!ref': 'A1' } }
      }
      */
   });

}