I have created a simple table in HTML file. Now I need to make it exported in PDF or Excel or CSV format in Angular JS? Is there any easy way to do that?
1 Answer
Here is an example which exports html table, you can save as pdf, csv, xlsx and other supported formats by browser.
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.exportData = function () {
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Report Example.xls");
};
$scope.items = [{
name: "John Smith",
email: "[email protected]",
dob: "1985-10-10"
}, {
name: "Jane Smith",
email: "[email protected]",
dob: "1988-12-22"
}, {
name: "Jan Smith",
email: "[email protected]",
dob: "2010-01-02"
}, {
name: "Jake Smith",
email: "[email protected]",
dob: "2009-03-21"
}, {
name: "Josh Smith",
email: "[email protected]",
dob: "2011-12-12"
}, {
name: "Jessie Smith",
email: "[email protected]",
dob: "2004-10-12"
}]
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js" type="text/javascript"></script>
</head>
<body>
<div ng-controller="myCtrl">
<button ng-click="exportData()">Export</button>
<br />
<div id="exportable">
<table width="100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>DoB</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td>{{item.email}}</td>
<td>{{item.dob | date:'MM/dd/yy'}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
5 Comments
Teddu
Thank you so much.. this worked :)
Teddu
Can we do this for pdf too?
nivas
you need
jsPdf library inorder to save your html as pdf, here is the example plnkr.co/edit/5NonsdQ23nXwFchV01sB?p=previewTeddu
ok thanks.. I have one more query.. If I need to export few specific rows based on class name, can we do so using fileSaver.js?
nivas
yes all you have to do is change this target
document.getElementById('exportable') to your document.getElementsByClassName('className') but do prefer Id over class since it is used only once