Using the MS Graph service to retrieve an Excel file from SharePoint

I'm looking to retrieve and download all xlsx files from a folder called myFolder. I have two functions available: getExcelSheets, which retrieves a list of all excel sheets, and @microsoft.graph.downloadUrl, accessed by calling the getFileContentById method. However, I am encountering difficulties in getting and converting the file into an xlsx format.

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;
}

If you have any tips on how to obtain and convert the file to xlsx, I would greatly appreciate it. Currently, I am using the following method to convert the buffer to xlsx:

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

Answer №1

If you are utilizing the Axios call within the function getFileContentById, you will receive a stream that can be used to write to a file or convert into an xlsx format. Here's an example of how this can be done:

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 for later use
      response.data.pipe(writer);
      
      // Or convert the binary data to xlsx using the XLSX library
      const sheet = XLSX.read(response.data, { type: "buffer" });
      console.log(sheet)
      /*
      {
        SheetNames: [ 'Sheet1' ],
        Sheets: { Sheet1: { A1: [Object], '!ref': 'A1' } }
      }
      */
   });

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a comparable function to JQuery's find() in Angular?

When working with Angular, I am looking to replicate the functionality of jQuery's find() method in order to achieve the following: var $vCard = $(stanza).find("vCard"); var img = $vCard.find('BINVAL').text(); var type = $vCard.find('T ...

Combining union types with intersection operators in Typescript

Here's a concept for an event handling system: type EventMap = Record<string, any>; type EventKey<T extends EventMap> = string & keyof T; type EventReceiver<T> = (params: T) => void; interface Emitter<T extends EventMap&g ...

Learn how to correctly infer a module's type in TypeScript using import.meta.glob

I attempted to utilize import.meta.glob to infer the correct type of module, but I am unsure of how to accomplish this. This is the structure of my directory. └─store └─reducer └─index.ts └─userSlice.ts ...

Monitoring a Typescript Class's Get() or Set() function using Jasmine Spy

While working with Jasmine 2.9, I have encountered no issues spying on both public and private functions, except for when trying to spy on a get or set function at the class level. private class RandomService { public dogsHealth = 0; private get pers ...

Testing VueJs components with Jest and Typescript: when the components are not mounted

Our team is in the process of developing an application using VueJs. Drawing from our past experience with Angular unit testing utilizing Jasmine and Karma, we have opted to implement Typescript for this VueJs project. Currently, I have created simple spe ...

Utilizing useRouteMatch with strongly-typed react-router components

When retrieving the match from my route using the hook in this manner: const match = useRouteMatch('/chat/:id'); I then intend to pass it down to a child component. However, when I attempt to do so, I encounter the following error: Type ' ...

Check the status of the caps lock key upon initialization of the directive

One challenge I am facing is how to determine the caps lock state when initializing a directive. The current setup only detects changes after a key press, but what if the user enters the page with caps lock already activated? Here is the existing code for ...

Waiting for the response to come by subscribing in Angular

I am encountering an issue while trying to subscribe to an Observable and assign data from the response. The problem is that my code does not wait for the response before executing the console.log(this.newIds) line, resulting in an empty value being logg ...

What is the ideal method for presenting JSON data retrieved from an API in a tabular format?

As a newcomer to Angular, I am working on extracting data from an API located at . How can I display this JSON data in a tabular format within my Angular application? Are there any adjustments needed for the data to be presented in a tabular form upon serv ...

Converting JSON to objects in Angular 2 using Typescript

Being new to Angular2 and Typescript, I am currently in the learning phase. I am trying to retrieve data from a REST service and then populate a list with this data obtained from the service. The API link I am using is http://jsonplaceholder.typicode.com/u ...

Is there a way to inject 'cmd' into the browser for Sentry (@sentry/nextjs package) by using a personalized webpack setup in Next.js?

My package json includes the following dependencies: "webpack": "5.58.1", "@sentry/nextjs": "6.13.3", "typescript": "4.0.5", "next": "11.0.1", After running next build without ...

In JavaScript or TypeScript, you can calculate the number of duplicate objects in an array by adding an "amount" property to each item

Currently, I have an array of items that contains duplicates. My goal is to count the duplicates and update one item with the total count while discarding the other duplicate. Here is my initial data: (simplified) [ { "id": "fishing_r ...

Express is encountering an issue where it is unable to interpret the property 'name' of an undefined element coming from

I am attempting to create a fullstack application using Node.js and Angular with Material UI. I have encountered an issue while working on my web resource management application. Currently, I am facing an error during the registration and data submission ...

mongoose memory leak attributed to jest

UPDATED 2020-09-14 I've encountered an issue with a test case I wrote. While the testcase passes, it raises a complaint about improper teardown and an open connection. Can anyone help identify the problem: Approach to Solving the Issue - Memory Leak ...

Creating a TypeScript function that automatically infers the type of the returned function using generics

Suppose I want to execute the generateFunction() method which will yield the following function: // The returned function const suppliedFunction = <T>(args: T) => { return true; }; // The returned function // This is how it can be used suppli ...

Utilize TypeScript with react-redux connect for seamless integration

As I attempt to create a React application in TypeScript using Redux and react-router-dom, I encountered some typing problems when integrating Redux. To address this issue, I decided to construct a minimal example containing only one page called test-page: ...

What are the reasons for deprecating bindToController in Typescript?

When I am creating an AngularJS directive using TypeScript, I typically use the bindToController property to bind parameters to the controller for easy access. export class MyDirective implements IDirective { controller = MyController; controllerA ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

The node.js command runs successfully in the terminal, however, it encounters issues when executed

Something strange is happening in my project. After updating all the development dependencies, my dev:server script stopped working. Now, when I try to run it using npm or yarn, I encounter the following error: npm run dev:server > <a href="/cdn-cg ...

"Capture input value changes and display the previous value when submitting a post. See an example of

Hi there! I'm facing 2 issues with my code, you can find a DEMO here When adding a product to the sale form, the input field for `description` changes for all products. Changing the input product in the sale does not reflect the change. I have shar ...