I want to add export table data in CSV, Excel, PDF format functionality in my app.
I am building app using angularjs 1.2.16.
Export data in Excel
I have used
<script src="https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js" type="text/javascript"></script>
to export table to XLS format using following code :
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "report.xls");
above code is working fine.
Export data in CSV, PDF
In the same way i want to export data in CSV and PDF format.
I have used http://www.directiv.es/ng-csv to export data in CSV but it is not working fine in ubuntu libre office (file is showing corrupted data).
Can anyone tell me how to export table data in CSV,Excel and PDF format in angularjs?
You can export data from AngularJS to XLS, XLSX, CSV, and TAB formats with Alasql JavaScript library with XLSX.js.
Include two libraries into the code:
alasql.min.js
xlsx.core.min.js
To export data to Excel format create a function in the controller code:
function myCtrl($scope) {
$scope.exportData = function () {
alasql('SELECT * INTO XLSX("mydata.xlsx",{headers:true}) FROM ?',[$scope.items]);
};
$scope.items = [{a:1,b:10},{a:2,b:20},{a:3,b:30}];
};
Then create a button (or any other link) in HTML:
<div ng-controller="myCtrl">
<button ng-click="exportData()">Export</button>
</div>
Try this example in jsFiddle.
To save data into CSV format use CSV() function:
alasql("SELECT * INTO CSV('mydata.csv', {headers:true}) FROM ?",[$scope.mydata]);
Or use TXT(), CSV(), TAB(), XLS(), XLSX() functions for proper file formats.
If you're satisfied with a CSV file, then the ngCsv module is the way to go. You don't load elements from the DOM but export an array directly. Here you can see a sample of ngCsv in action.
The html:
<h2>Export {{sample}}</h2>
<div>
<button type="button" ng-csv="getArray" filename="test.csv">Export</button>
</div>
and the js:
angular.module('csv', ['ngCsv']);
function Main($scope) {
$scope.sample = "Sample";
$scope.getArray = [{a: 1, b:2}, {a:3, b:4}];
}
saveAs; To change the registered file extension, for example: "f:\folder\report.html" directory?
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8" });
saveAs(blob, "report.xls");
I've worked through several approaches and concluded the following, typesafe (DefinitelyTyped):
exportAsExcel(tableId: string, fileName: string, linkElement: any) {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
base64 = function (s) {
return window.btoa(decodeURI(encodeURIComponent(s)));
},
format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
});
};
// get the table data
var table = document.getElementById(tableId);
var ctx = {
worksheet: fileName,
table: table.innerHTML
};
// if browser is IE then save the file as blob, tested on IE10 and IE11
var browser = window.navigator.appVersion;
if ((browser.indexOf('Trident') !== -1 && browser.indexOf('rv:11') !== -1) ||
(browser.indexOf('MSIE 10') !== -1)) {
var builder = new MSBlobBuilder();
builder.append(uri + format(template, ctx));
var blob = builder.getBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
window.navigator.msSaveBlob(blob, fileName + '.xlsx');
} else {
var element = document.getElementById(linkElement);
var a = document.createElement('a');
a.href = uri + base64(format(template, ctx));
a.target = '_blank';
a.setAttribute('download', fileName + '.xlsx');
document.body.appendChild(a);
a.click();
}
toastr.success("Awesome!", "We've created an Excel report for you and you should get it as a download in your browser.");
}
Kudos go to those who contributed of course in the various article.s
we can export data from a table into various format including
Json, Xml, Pdf .....
You can find detailed explanation http://www.prathapkudupublog.com/2015/10/angular-export-to-table.html
Note: This implementation would not run in IE
What do you need?
Angularjs
Jquery.js
Files referenced below
tableExport.js,JqueryBase64.js,html2canvas.js,base64.js,Jspdf.js,sprintf.js
<script type="text/javascript">
var myAppModule = angular.module('myApp', []);
myAppModule.controller('myCtrl', function ($scope) {
$scope.exportData = function () {
$('#customers').tableExport({ type: 'json', escape: 'false' });
};
$scope.items = [
{
"FirstName": "Prathap",
"LastName": "Kudupu",
"Address": "Near Anjana Beach"
},
{
"FirstName": "Deepak",
"LastName": "Dsouza",
"Address": "Near Nariman Point"
}
];
});
Related
I have been researching all afternoon and playing around with various solutions I have found on the internet and Stack OverFlow to try to keep the gridlines turned on when I export data from my HTML webpage but to no avail. I am really trying to avoid using a plug in and something this simple shouldn't require on in my opinion. I'm actually shocked that this is proving as challenging as it is. Anyway...I found this code....
function exportTableToExcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
And coupled with this HTML.....
<table id="tblData" class="table10">
<tr>
<th class="title36">Description</th>
</tr>
</table>
<button onclick="exportTableToExcel('tblData')"</button>
It all works beautifully! Except when I open the file the gridlines are gone and the user would have to go the view tab and turn the gridlines back on every time. Is there a setting I can change somewhere that will allow this?
The second example in this SO works...but I have a problem whereby I need to use a button and not an input button....for styling purposes...and then in doing so because the solution is written as a var and not a function....I had trouble working it out. So I know what I'm trying to do is possible...I just can't quite figure out how to work out doing this as Javascript without a plugin. I'm fairly new at Javascript so thanks in advance for any pointers...perhaps how I can rewrite the second solution as a function?
This is the code that I found that works....
<script type="text/javascript">
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
But I need to rewrite it so that I can call it in like the first function that is referenced at the beginning of my code above. Thanks again for any pointers or thoughts.
After more research I realized the second piece of code was the answer. I simply needed to update my HTML button reference as follows...
<button type="button" onclick="tableToExcel('tblData',)" class="class"><div class="class1"><h3 class="class2">Export To Excel</h3></div></button>
I want to add a comment on Header fields of CSV File generated by Javascript
Also, I have Searched out for these requirements but can't find any solutions
Here is code that's using for generating CSV File using Javascript
var data = [
['123'],
['346'],
['789'],
['Test1'],
['Test2']
];
function download_csv() {
var csv = 'ID\n';
data.forEach(function(row) {
csv += row.join(',');
csv += "\n";
});
console.log(csv);
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'test.csv';
document.getElementById('container').appendChild(hiddenElement);
hiddenElement.click();
}
<button onclick="download_csv()">Download CSV</button>
<div id="container" style="display:none;"></div>
I want to Add Header Comment like Here
There is no standard way to achieve this using CSV. However, you can resort to writing the file as XLXS as commenting is an application specific feature.
I am using javascript to generate a large table (of around 15000 rows) and export it to excel. I am converting it into a blob and then exporting using the following code.
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) tableNode = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: tableNode.innerHTML}
str = base64(format(template, ctx));
var blob = b64toBlob(str, "application/vnd.ms-excel");
var blobUrl = URL.createObjectURL(blob);
window.location = blobUrl;
}
It is working fine. However, I am not able to vertically align the text in the excel sheet to the top. I have tried multiple plugins and could not find anything suitable. The table contains
merged cells
hyperlinks
large amount of data
text alignment
I require a solution which will generate the excel file quickly and will support all features
Tried approaches:
- SheetJS was slow since I iterated over the cells and added hyperlinks to a cell in each row.
- Xlsx does not support hyperlinks.
Please let me know a suitable solution. Thanks in advance!
I was able to achieve this by simply adding css to the td vertical-align: top to the table.
Thanks :)
I have a requirement where I need to use export to excel functionality in angularjs. For this I am using saveAs(blob, "FileName"+ ".xls"); which is working fine.
I need to export the data excluding some tags, like images or any control (e.g. button or text area), basically I need only text content.
scope.exportData = function (item) {
if (document.getElementById(item) != null) {
var tableContent = document.getElementById(item).querySelector('table').outerHTML;
var blob = new Blob([tableContent], {
type: "application/vnd.openxmlformats-officedo***ent.spreadsheetml.sheet;ch***t=utf-8"
});
saveAs(blob, item + ".xls");
}
else
alert("No data to export");
};
I am getting strange Issue that whenever I am exporting the data in csv which have a currency symbol, It has added junk extra character in the data beside the currency symbol.
For example if My data = France - Admin Fee 1 x £100
I am getting the result like = France - Admin Fee 1 x £100 when i open this in Excel. My code is :
<html>
<head>
<script type="text/javascript">
function CreateCSV()
{
var buffer = "France - Admin Fee 1 x £100";
buffer = "\"" + buffer + "\"";
// buffer = "" + euro; //"\u2034";
var uri = "data:text/csv;charset=UTF," + encodeURIComponent(buffer);
var fileName = "InvoiceData.csv";
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
link.setAttribute("href", uri);
link.setAttribute("download", fileName);
}
else if (navigator.msSaveBlob) { // IE 10+
link.addEventListener("click", function (event) {
var blob = new Blob([buffer], {
"type": "data:text/csv;charset=UTF;"
});
navigator.msSaveBlob(blob, fileName);
}, false);
}
else {
// it needs to implement server side export
}
link.innerHTML = "Export to CSV";
link.click();
}
</script>
</head>
<body>
<input type="button" value="Download CSV" onclick="CreateCSV()" />
</body>
</html>
When i open the same in notepad. I cannot see the junk character. I am very thankful if you can get me a work around.
The character set should probably be UTF-8. Also check the unicode for the £, I do believe it is u2034. You can find a chart here, and it lists it as U+00A3. If you have something more advanced than just Notepad, like Notepad++ for example, check the encoding type when you open the time. Excel can be finicky.