Convert Excel into Memory Stream and download via AngularJS

3 min read 07-10-2024
Convert Excel into Memory Stream and download via AngularJS


Transform Your Excel Data: Downloading from AngularJS with MemoryStream

Excel files are ubiquitous in the business world, but sometimes we need to generate them dynamically within a web application. This is where the combination of AngularJS and MemoryStream comes in handy. This article will guide you through the process of converting Excel data into a MemoryStream and subsequently downloading it within your AngularJS application.

Understanding the Problem

Imagine you have a web application that needs to display data in a user-friendly format. You need to allow users to download this data as an Excel file, but the data itself is generated dynamically within the application. How do you convert this data into a downloadable Excel file without storing it on the server?

The Solution: MemoryStream

The solution lies in leveraging a MemoryStream. A MemoryStream is essentially a stream of data stored in memory, allowing you to manipulate and manage data without writing it directly to a physical file. This is perfect for our scenario as we can generate the Excel data on the fly and store it in a MemoryStream, ready for download.

Let's Dive into the Code

// AngularJS Controller
app.controller('MyController', function($scope, $http, $window) {

  $scope.downloadExcel = function() {
    // Fetch data from your service/API
    $http.get('/api/data')
      .then(function(response) {
        // Convert data to Excel format (using a library like SheetJS)
        const workbook = XLSX.utils.book_new();
        const worksheet = XLSX.utils.json_to_sheet(response.data);
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

        // Convert Workbook to Binary String
        const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });
        const data = new Blob([s2ab(excelBuffer)], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

        // Create a download link and trigger the download
        const downloadLink = document.createElement('a');
        downloadLink.href = window.URL.createObjectURL(data);
        downloadLink.download = 'data.xlsx';
        downloadLink.click();
      });
  };

  // Utility function to convert String to ArrayBuffer
  function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i < s.length; i++) {
      view[i] = s.charCodeAt(i) & 0xFF;
    }
    return buf;
  }
});

Key Steps Explained:

  1. Fetch Data: First, we use AngularJS's $http service to retrieve the data from a service or API endpoint.
  2. Data Conversion: We employ a library like SheetJS (or similar Excel manipulation libraries) to convert our data into the desired Excel format (in this case, an XLSX file).
  3. MemoryStream Creation: We use the XLSX.write() method to convert the workbook into a binary string, which is then transformed into a Blob object using new Blob(). The Blob object represents the Excel data in the form of a MemoryStream.
  4. Download Initiation: We create a temporary download link element, set its attributes (href, download), and programmatically trigger a click event to initiate the download.

Additional Insights:

  • Library Selection: Choose an Excel library that aligns with your project requirements and programming language. Some popular choices include SheetJS, ExcelJS, and XlsxWriter.
  • Customization: You can further customize your Excel file by adding headers, formatting cells, or using formulas, all within the chosen Excel library's functionality.
  • Error Handling: Remember to implement robust error handling to gracefully manage scenarios where data retrieval fails or Excel conversion errors occur.

Conclusion

Using MemoryStream and AngularJS, you can efficiently create and download Excel files directly from your application, empowering your users with a seamless and dynamic data experience. By leveraging the power of these technologies, you can enhance your application's capabilities and cater to various user needs.

Resources: