Export table from html to excel with js (orentation problem) - javascript

Cant pass orientation landscape parameter to excel, though can pass zoom parameter just fine
Tried to include #page solution,tried to pass page orientation parameter tried various examples and solutions.
PS: working with dynamical tables client side, the table itself passes fine with their values and even zoom parameter passes, problem it with orientation
Edited code, beginning was cut due to code checker
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">' +
'<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"><head>' +
'<!--[if gte mso 9]>' +
'<xml><x:ExcelWorkbook>' +
'<x:ExcelWorksheets>' +
'<x:ExcelWorksheet>' +
'<x:Name>{worksheet}' +
'</x:Name>' +
'<x:WorksheetOptions>' +
'<x:Zoom>100</x:Zoom>'+
'<x:DisplayGridlines/>' +
'</x:WorksheetOptions>' +
'</x:ExcelWorksheet>' +
'</x:ExcelWorksheets>' +
'</x:ExcelWorkbook>' +
'</xml><![endif]-->' +
'</head><body><table><caption>{table}</caption></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("examplecopy")
var ctx = {
worksheet: name || 'Worksheet',
table: table.innerHTML
}
window.location.href = uri + base64(format(template, ctx))
}
})()

<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>

<script>
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<html xmlns:v="urn:schemas-microsoft-com:vml"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> <meta http-equiv=Content-Type content="text/html; charset=utf-8"> <meta name=ProgId content=Excel.Sheet> <meta name=Generator content="Microsoft Excel 11">'+
' <!--[if gte mso 9]><xml><o:DocumentProperties><o:Author>Pat Willener</o:Author><o:Company>Good Day Books</o:Company>'+
' </o:DocumentProperties><o:OfficeDocumentSettings><o:RelyOnVML/><o:AllowPNG/></o:OfficeDocumentSettings>'+
' </xml><![endif]-->'+
' <style><!--table {mso-displayed-decimal-separator:"\.";mso-displayed-thousand-separator:"\,";} #page {mso-header-data:"&CInventory"; mso-footer-data:"Page &P of &N";'+
' margin:.31in 0in .31in 0in; mso-header-margin:0in; mso-footer-margin:0in; mso-page-orientation:landscape;} --></style>'+
' <!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Inventory</x:Name><x:WorksheetOptions><x:Print><x:ValidPrinterInfo/>'+
' <x:PaperSizeIndex>9</x:PaperSizeIndex><x:HorizontalResolution>600</x:HorizontalResolution><x:VerticalResolution>600</x:VerticalResolution></x:Print><x:Selected/>'+
' <x:Panes><x:Pane><x:Number>1</x:Number><x:ActiveRow>1</x:ActiveRow></x:Pane></x:Panes><x:ProtectContents>False</x:ProtectContents><x:ProtectObjects>False</x:ProtectObjects>'+
'<x:ProtectScenarios>False</x:ProtectScenarios></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets><x:WindowHeight>8835</x:WindowHeight><x:WindowWidth>15180</x:WindowWidth>'+
' <x:WindowTopX>120</x:WindowTopX><x:WindowTopY>105</x:WindowTopY><x:ProtectStructure>False</x:ProtectStructure><x:ProtectWindows>False</x:ProtectWindows></x:ExcelWorkbook>'+
'</xml><![endif]-->'+
' <title>Inventory</title>'+
'</head><body><table><caption>{table}</caption></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("examplecopy")
var ctx = {
worksheet: name || 'Worksheet',
table: table.innerHTML
}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
this one worked for me

Related

Javascript to export HTML table to Excel - Add options

I have the following piece of code which exports my table to Excel:
<script>
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>'
+ '<ProtectObjects>False</ProtectObjects>'
+ '<ProtectScenarios>False</ProtectScenarios>'
+ '</x:ExcelWorksheet>'
// + '<Header x:Data="&CTHIS IS THE HEADER (CENTER)"/>'
// + '<Footer x:Data="&RTHIS IS THE FOOTER (RIGHT)"/>'
// + '<Layout x:Orientation="Landscape" x:CenterHorizontal="1"/>'
+ '</x:ExcelWorksheets>'
+ '</x:ExcelWorkbook>'
+ '</xml>'
+ '<![endif]-->'
+ '</head>'
+ '<body>'
+ '<table border=1>{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>
I have two issues:
Issue the First: The 3 lines that are commented out do not seem to take effect anywhere I place them. If I can get these options implemented, that would be outstanding. (Yes, I realize I must un-comment them to work...)
Issue the Second: When exporting the table, the filename ends up as whatever.xls.XLS. I'm not sure how the extension is being duplicated.
Please help.

Export excel in angular js without using third party library

I have list of items in scope, that is showing UI in html table using ng-repeat in table data, Below i have tried export table data to excel but that is showing only first page rows i want to show all the records in the list. i have all the data in scope using that i have to do. Is there any other wat to achieve this?
app.controller("ErrorDetailController", [
"$scope", "$location", "$routeParams", "messageService", "errorService", "repositoryService", , "sharedPageService",
function ($scope, $location, $routeParams, messageService, errorService, repositoryService,sharedPageService, **Excel, $timeout**)
{ $scope.exportToExcel = function (tableId) { // ex: '#my-table'
debugger;
var exportHref = Excel.tableToExcel(tableId, 'sheet name');
$timeout(function () { location.href = exportHref; }, 100); // trigger download
}
}
]);
app.factory('Excel', function ($window) {
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(unescape(encodeURIComponent(s))); },
format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) };
return {
tableToExcel: function (tableId, worksheetName) {
var table = $(tableId),
ctx = { worksheet: worksheetName, table: table.html() },
href = uri + base64(format(template, ctx));
return href;
}
};
})
I have done with below code, it may be helpful to some one. Thanks....
$scope.exportExcel = function () {
var header = ["columnName1","columnName2"];
var column = ["data1","data2"];
Excel.jsonToExcel($scope.list, header, column, 'sheetname', 'filename.xls');
};
};
eaiApp.factory('Excel', function ($window) {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<?xml version="1.0"?>\n' +
'<ss:Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"\n' +
'xmlns:o="urn:schemas-microsoft-com:office:office"\n' +
'xmlns:x="urn:schemas-microsoft-com:office:excel"\n' +
'xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"\n' +
'xmlns:html="http://www.w3.org/TR/REC-html40">\n' +
'<ss:Styles>\n' +
'<ss:Style ss:ID="s62">\n' +
'<ss:Borders>\n' +
'<ss:Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>\n' +
'<ss:Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>\n' +
'<ss:Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>\n' +
'<ss:Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>\n' +
'</ss:Borders>\n' +
'</ss:Style>\n' +
'<ss:Style ss:ID="s63">\n' +
'<ss:Borders>\n' +
'<ss:Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>\n' +
'<ss:Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>\n' +
'<ss:Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>\n' +
'<ss:Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>\n' +
'</ss:Borders>\n' +
'<ss:Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000" ss:Bold="1"/>\n' +
'<ss:Interior ss:Color="#F4B084" ss:Pattern="Solid"/>\n' +
'</ss:Style>\n' +
'</ss:Styles>\n' +
'<ss:Worksheet ss:Name="{SheetName}">\n' +
'<ss:Table>\n',
};
return {
jsonToExcel: function (scopeData, header, column,sheetName, fileName) {
var data = typeof scopeData != "object" ? JSON.parse(scopeData) : scopeData;
if (data.length != 0) {
var headerRow = '<ss:Row>\n';
for (var i = 0; i < header.length; i++) {
delete data[0].$$hashKey;
headerRow += ' <ss:Cell ss:StyleID="s63">\n';
headerRow += ' <ss:Data ss:Type="String">';
headerRow += header[i] + '</ss:Data>\n';
headerRow += ' </ss:Cell>\n';
}
headerRow += '</ss:Row>\n';
var xml = template.replace('{SheetName}', sheetName);
xml += headerRow;
for (var row = 0; row < data.length; row++) {
delete data[row].$$hashKey;
xml += '<ss:Row>\n';
for (var col = 0; col < column.length; col++) {
xml += ' <ss:Cell ss:StyleID="s62">\n';
xml += ' <ss:Data ss:Type="String">';
xml += data[row][column[col]] + '</ss:Data>\n';
xml += ' </ss:Cell>\n';
}
xml += '</ss:Row>\n';
}
xml += '\n</ss:Table>\n' +
'</ss:Worksheet>\n' +
'</ss:Workbook>\n';
var contentType = 'application/octet-stream';
var uri = 'application/octet-stream,' + escape(xml);
var link = document.createElement("a");
var blob = new Blob([xml], {
'type': contentType
});
var myNav = navigator.userAgent.toLowerCase();
var isIE = (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
if (navigator.appVersion.toString().indexOf('.NET') > 0) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
}
else {
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
else
alert("No records to export.");
return;
}
};

export as .xls file not work when large data

I am using the javascript code for export html table to .xls file.Its work in crome and when data is not large.But when data is large then it shows me error like
The code which i have used for export the table as .xls file is as below:
function exportDiv() {
//working on crome perfectly
var dt = new Date();
var day = dt.getDate();
var month = dt.getMonth() + 1;
var year = dt.getFullYear();
var hour = dt.getHours();
var mins = dt.getMinutes();
var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
var a = document.createElement('a');
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('tbl-1');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
a.download = 'exported_table_' + postfix + '.xls';
a.click();
e.preventDefault();
}
I have also sufficient 4 gb ram so i think its not memory limit problem.
Can you please help me for how to export large data?
Edit: I ahve used this way also
var table_html=encodeURIComponent(table_div.outerHTML);
But still same error come.
Most likely you've hit the 2 MB URL limit in Chrome. You can read about it here - issue link. I suggest you try your app in Firefox, if it works, then that is the issue.
excel sheet has got a character limit for 32767 characters similar to that of an excel cell.
for reference check this link : http://office.microsoft.com/en-in/excel-help/excel-specifications-and-limits-HP010073849.aspx
I have called the tableToexcel function on button click like as below and it is working fine in firefix.
<a id="dlink" style="display:none;"></a>
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]--></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, filename) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
document.getElementById("dlink").href = uri + base64(format(template, ctx));
document.getElementById("dlink").download = filename;
document.getElementById("dlink").click();
}
})();

Exporting HTML tables to Excel (.xls) in a separate sheet

I've got a simple HTML page (generated by an external application) that contains a table view.
I am trying to scrape off the tables from the page and put them in an Excel workbook.
I have managed to put the whole HTML contents in a workbook by using the method available here.
Code from the related question:
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]--></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))
}
})()
JSFiddle
The method however does not support multiple spreadsheets. What I need is for every HTML table being in it's own SpreadSheet in the same Excel workbook. Something like this:
I have tried to create a sample Excel document with two spreadsheets and then reverse engineer it by looking at an export in .html format. Unfortunately I failed to understand how to recreate the connection betwee a workbook and it's sheets.
As far as I can understand the format() function does the 'magical' combining of the worksheet data and the Excel template. The function looks very cryptic to me, so I have no idea how to go about modifying it.
What I need as an end game is having the possibility to call something like.
tableToExcel(document.getElementsByTagName('table'), 'Workbook Name');
Any ideas if this is at all possible, and if so - how to go about making it happen?
Checkout this blog post: http://www.kubilayerdogan.net/?p=218
$(document).ready(function() {
$("#btnExport").click(function(e) {
//getting values of current time for generating the file name
var dt = new Date();
var day = dt.getDate();
var month = dt.getMonth() + 1;
var year = dt.getFullYear();
var hour = dt.getHours();
var mins = dt.getMinutes();
var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
//creating a temporary HTML link element (they support setting file names)
var a = document.createElement('a');
//getting data from our div that contains the HTML table
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('dvData');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
//setting the file name
a.download = 'exported_table_' + postfix + '.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
});
});
You can see it in action in jsfiddle: http://jsfiddle.net/kublaios/8ZQN4/1/

Export dynamic html table to excel in javascript in firefox browser

Want to Export dynamic html table to excel in javascript is there any way can i do do in firefox browser without using activex object in code .please help me
Here's a function for doing this in Firefox with JavaScript, assuming the user has Excel installed on their machine:
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]--></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))
}
})()
jsFiddle live example:
http://jsfiddle.net/insin/cmewv/
You can dynamically generate the Excel file in SpreadsheetDataXML format which allows you to custom the table, cell styles and format in HTML syntax.
To make this work in IE you'll need to use Blob object and then call msSaveBlob method.
For FF and Chrome, you can just change the data of href to data:application/vnd.ms-excel
function fnExcelReport() {
var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';
tab_text = tab_text + '<x:Name>Test Sheet</x:Name>';
tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
tab_text = tab_text + "<table border='1px'>";
tab_text = tab_text + $('#myTable').html();
tab_text = tab_text + '</table></body></html>';
var data_type = 'data:application/vnd.ms-excel';
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
if (window.navigator.msSaveBlob) {
var blob = new Blob([tab_text], {
type: "application/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, 'Test file.xls');
}
} else {
$('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
$('#test').attr('download', 'Test file.xls');
}
}
Working example: http://jsfiddle.net/h42y4ke2/21/
YT tutorial: https://www.youtube.com/watch?v=gx_yGY6NHkc
AFAIK there's no library for creating a real excel file in JavaScript but you might try and export the table in HTML to a file with .xls extension.
There is an extension table2clipboard for firefox. You can also generate csv output from DOM tree manually and let user save it as csv file. Excel can import from CSV.

Categories

Resources