Generating CSV Report from Base64 Encoded data

In many web applications utilized by administrators or business professionals, a common requirement is to enable the seamless download of data in CSV or Excel formats. This functionality is crucial for analyzing performance, reviewing statistics, and various other use cases. Let's explore how to achieve this using Angular coupled with backend APIs for data transmission.

Prerequisites:

  • Basic familiarity with the Angular framework

  • Node.js installed on your local machine

To begin, clone the repository from AngularCodeHub
git clone https://github.com/UlbertAO/AngularCodeHub

Open the project in your preferred code editor (e.g., VSCode) and run:
npm install

Once the installation completes, launch the application using:
ng serve -o

This will promptly open the application in your default browser.

Navigate to the "ReportExtraction" route to follow.

Implementing Backend API Interaction

Within the service, create a method to communicate with the backend API and retrieve the data necessary for generating a CSV file.

There are multiple methods to pass a file via an API endpoint to a web application, such as base64 encoding, binary data, or file streaming. For this demonstration, we'll use base64 encoding due to its:

  • Seamless integration with JSON/XML

  • Prevention of binary corruption

  • Universal acceptance across different systems due to its standard character set

Consider the following method within your service:

  getReport(
    payload: ReportExtractionReqModal
  ): Observable<ReportExtractionResModal> {
    // return this.http.post<ReportExtractionResModal>(
    //   this.appSetting.baseURLs?.ReportExtraction,
    //   payload
    // );
    return this.http.get<ReportExtractionResModal>(
      '../../../assets/response/reportExtraction.json'
    );
  }

For simplicity in our demonstration, a dummy response with base64-encoded file data is utilized.

Note: The provided payload won't affect the data, as the API is expected to filter data based on the request payload and return the filtered data in the response.

Once the API call is made and the response is received, the following code snippet can be utilized to convert the base64-encoded data into a CSV format:

let binary_string = window.atob(data.responses);
const blob = new Blob([binary_string], { type: 'text/csv' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'Report.csv';
link.click();

This code snippet facilitates the conversion and download of the received base64-encoded data as a CSV file.

Decode base-64 encoded data using window.atob() and pass decoded data to Blob constructor which will be used to create blob object, also specify MIME type as 'text/csv', indicating that it's a CSV file.

Hope you find this article helpful.