download a sharepointlist in typescript

One way to download a SharePoint list in TypeScript is to use the SharePoint REST API and the file-saver library. Here's an example code snippet:

index.ts
import { saveAs } from 'file-saver';

const listName = 'MyList';
const siteUrl = 'https://contoso.sharepoint.com/sites/mySite';
const apiUrl = `${siteUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=File&$expand=File`;

fetch(apiUrl, {
  method: 'GET',
  headers: {
    Accept: 'application/json;odata=verbose',
    'Content-Type': 'application/json;odata=verbose',
  },
})
  .then(response => response.json())
  .then(data => {
    const fileUrl = data.d.results[0].File.ServerRelativeUrl;

    fetch(`${siteUrl}/${fileUrl}`, {
      method: 'GET',
      headers: {
        Accept: 'application/json;odata=verbose',
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-Requested-With': 'XMLHttpRequest',
      },
    })
      .then(response => response.blob())
      .then(blob => {
        saveAs(blob, 'MyList.xlsx'); // or any other file format
      });
  });
895 chars
31 lines

Explanation:

The code first gets the SharePoint list items using the SharePoint REST API with the $select=File and $expand=File query options to include the File object in the response.

It then extracts the ServerRelativeUrl property of the File object and uses it to download the file using another fetch request.

Finally, it converts the response into a Blob object and passes it to the saveAs method from the file-saver library to trigger the download.

gistlibby LogSnag