Download CSV file from web API in AngularJs
Example in detail for download CSV file using
JSON data.
HTML
Code looks like -
<div class="text-right">
<a href="javascript:void(0)" ng-click="download()">Download</a>
</div>
AngularJs
code looks like -
$scope.download = function () {
var request = {};
var userId = localStorage.getItem("UserId");
request.PageNo =
$scope.PageNo;
request.PageSize
= $scope.PageSize;
ControllerService.Post("/User/GetUserList",
{ obj: request, userID: userId }, function (status, response) {
if (status && response.Message == "UNAUTHORIZED") {
//unthorized access
$rootScope.$emit('Logout', {});
}
else if (response.Status && status) {
var row = response.UserList;
var Head = [[
'User App Date',
'User ID',
'Remarks'
]];
for (var item = 0; item < row.length; ++item) {
Head.push([
row[item].CreatedOn,
row[item].UserID,
row[item].Remark
]);
}
var csvRows = [];
for (var cell = 0; cell < Head.length; ++cell) {
csvRows.push(Head[cell].join(','));
}
var csvString = csvRows.join("\n");
let csvFile = new Blob([csvString], { type: "text/csv" });
let downloadLink = document.createElement("a");
downloadLink.download = 'UserList.csv';
downloadLink.href =
window.URL.createObjectURL(csvFile);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
});
}
The result looks like -