Introduction
In working on different application, one is common requirement for most of the applications is to export data and save it in a CSV file with data. This will help to organise the data and generates proper formatted report.
A CSV file contains data values separated by commas. It has an extension of .csv.
Prerequisite is to have to running an angular project, if you are new to angular then please visit to set up a new angular project.
To make it clear and straightforward, to download a CSV file both the frontend and backend will be involved.
- Front-end – This is implemented using Angular and is responsible for making a GET request to the back-end and saving the data as a CSV file.
- Back-end – This is responsible for querying the data and sending it to the front-end when requested.
In this blog, we will focus on the front-end side only. Also, with the detail of which type of data will get from the backend on our request.
Enough theory; let’s get our hands dirty by writing some code.
Implementation
get API request
Firstly, we will understand the function used to request data from backend that need to save in csv file before download. Below is one function that can be put in service file to request data.
downloadCSV(data: any): Observable<any> {
return this.http.get<any>(this.backendUrl, data ,{ observe: 'body', responseType: 'text' as 'json' })
}
The downloadCSV method receives the data as a buffer from the back-end. By setting the GET method’s option responseType to text as JSON, we can pass it back to our component as is, constructing then a Blob object with it.
After all the above, we will focus on component code to call this method and save it to a CSV file.
If you want to read more about Blobs, click here.
Method to download file
Now, in component need to call the below function to download the CSV file. In downloadFile function, there’s another method called which belongs to the service. Here is a response which will be get from the backend as text in JSON format of blob type. Now element is created with href as ‘data: text/csv, ‘ with response in append.
downloadFile() {
this.demoService.downloadCSV(payload).subscribe(
(response) => {
const a = document.createElement("a");
a.href = "data:text/csv," + response;
let filename = "sampleCSVDownload";
a.setAttribute("download", filename + ".csv");
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
)
}
That’s it; all the data will be downloaded as a CSV file named sampleCSVDownload.csv in our use case.
Conclusion
The above method will help you to download csv file with data provided by the backend in blob type. In the programming world, there might be a hundred ways to solve a problem, but we choose one solution to implement it in a clean way. I hope that this article helped you to do so.
For more tech blogs, please visit Knoldus Blogs. Also, please follow our LinkedIn page- FrontEnd Studio
Enjoy Coding…