#atom
#snippet

Content

React implementation for downloading binary Excel data from an authenticated API endpoint, with support for mock data during development/testing.
This snippet assumes the backend endpoint returns the binary data from the file.

Key Points

Code Example

function ExcelDownloadButton({ useMock = false }) {
  const handleDownload = async () => {
    try {
      let blob;
      let fileName = 'downloaded-file.xlsx';

      if (useMock) {
        // Mock implementation
        blob = mockExcelData();
      } else {
        // Real API call with auth
        const response = await fetch('https://api.example.com/excel', {
          method: 'GET',
          headers: {
            'Authorization': 'Bearer token-here',
          },
        });
        
        if (!response.ok) throw new Error(`Error: ${response.status}`);
        blob = await response.blob();
        
        // Extract filename if available
        const contentDisposition = response.headers.get('Content-Disposition');
        if (contentDisposition) {
          fileName = extractFilenameFromHeader(contentDisposition);
        }
      }
      
      // Create and trigger download
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('Download failed:', error);
    }
  };

  return <button onClick={handleDownload}>Download Excel</button>;
}

Connections

References


Sources: