DEV Community

Cover image for View & Download 🧮 Excel File in React from a URL
Sarwar Hossain
Sarwar Hossain

Posted on

View & Download 🧮 Excel File in React from a URL

Displaying Excel data in a React application dynamically from a URL is a powerful feature

Prerequisites:

Before we begin, make sure you have the following installed:

  • React (Latest version)
  • XLSX.js (for parsing Excel files)

Create a new component ExcelView.tsx to fetch and parse the Excel file.


import * as XLSX from 'xlsx';
const ExcelView = () => {
  const excelFile =
    'https://res.cloudinary.com/dt7w8y7xj/image/upload/v1695779773/text_wzqj5r.xlsx';

  const parseExcelFile = () => {
    // Fetch the Excel file from the imported path
    fetch(excelFile)
      .then((response) => response.arrayBuffer()) // Read file as ArrayBuffer
      .then((fileBuffer) => {
        const workbook = XLSX.read(fileBuffer, { type: 'array' });
        const sheetName = workbook.SheetNames[0]; // Get the first sheet
        const sheet = workbook.Sheets[sheetName];
        const data = XLSX.utils.sheet_to_json(sheet); // Convert the sheet to JSON
        return data;
      })
      .catch((error) => console.error('Error parsing Excel file:', error));
  };

  // Parse the file immediately when the component is rendered

  return (
    <div className=" p-2 md:p-6 bg-gray-100 min-h-screen">
      <h1 className="text-3xl font-bold text-gray-700 text-center mb-8">
        View Excel File
      </h1>

      {parseExcelFile().length > 0 ? (
        <div className="overflow-x-auto">
          <table className="min-w-full bg-white border border-gray-300 rounded-lg shadow-md">
            <thead>
              <tr className="bg-gray-200 text-gray-600 uppercase text-sm leading-normal">
                {Object.keys(parseExcelFile()[0]).map((key) => (
                  <th key={key} className="py-3 px-6 text-left">
                    {key}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="text-gray-700 text-sm">
              {parseExcelFile().map((row, index) => (
                <tr
                  key={index}
                  className={`border-b border-gray-300 ${
                    index % 2 === 0 ? 'bg-gray-50' : 'bg-white'
                  }`}
                >
                  {Object.values(row).map((cell, i) => (
                    <td key={i} className="py-3 px-6 text-left">
                      {cell}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <p className="text-gray-500 text-center mt-8">Loading Excel data...</p>
      )}
    </div>
  );
};

export default ExcelView;

Enter fullscreen mode Exit fullscreen mode

Download an Excel File in React with Proper MIME Types


const handleDownload = async (url: string, filename: string) => {
  try {
    if (!url) {
      message.error('Download URL not found');
      return;
    }

    const response = await fetch(url, {
      headers: {
        Accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/pdf, video/mp4',
      },
    });

    if (!response.ok) {
      throw new Error('Download failed');
    }

    const contentType = response.headers.get('content-type');
    const blob = await response.blob();

    // Set the correct MIME type for Excel files
    const blobOptions = {
      type:
        contentType ||
        (filename.endsWith('.xlsx')
          ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          : blob.type),
    };
    const downloadUrl = window.URL.createObjectURL(new Blob([blob], blobOptions));

    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // Clean up the URL object
    window.URL.revokeObjectURL(downloadUrl);
    message.success('Download started successfully');
  } catch (error) {
    console.error('Error downloading file:', error);
    message.error('Failed to download file. Please try again.');
  }
};


Enter fullscreen mode Exit fullscreen mode

Now use it in your component


<button onClick={() => handleDownload('https://example.com/sample.xlsx', 'sample.xlsx')}>
  Download Excel File
</button>

Enter fullscreen mode Exit fullscreen mode

Conclusion:

This approach allows you to dynamically load and display Excel data in a React app using XLSX.js and downloaded correctly in a React application

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free