How to download an excel file from the sharepoint url

• Another step I tried is using the "Fetch" function of javascript, i am making an API call to the URL where the Excel file exists and trying to create an object from the response, but that didn't work.

So, this is the scenario in which I am stuck right now, I am trying to download the Excel file from the SharePoint URL which is not happening, Thanks for helping.

To download an Excel file from a SharePoint URL using JavaScript, you can follow these steps. Using the fetch function in JavaScript to download the file and then creating an anchor tag to trigger the download event can work. Here’s a detailed approach to achieve this:

  1. Create a fetch request to get the file data.
  2. Convert the response into a Blob object.
  3. Create a URL for the Blob object.
  4. Create an anchor tag and trigger the download.
function downloadExcelFile() {
  const sharepointFileUrl = "YOUR_SHAREPOINT_FILE_URL";

  fetch(sharepointFileUrl)
    .then(response => {
      if (!response.ok) {
        throw new Error("Network response was not ok " + response.statusText);
      }
      return response.blob();
    })
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      a.download = "file.xlsx"; // Set the file name here
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
    })
    .catch(error => {
      console.error("There has been a problem with your fetch operation:", error);
    });
}