Export dynamic html table to excel in javascript in firefox browser - javascript

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.

Related

How can I export a Excel file using Javascript?

I need to export data in '.XLSX' file for Chrome browser below code is working fine for IE.
But code in else condition is creating download.xls file Chrome browser
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
Below is the code used on Button Click :
function fnExcelReport()
{
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
tab = document.getElementById('headerTable'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"ABCD.xlsx");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
Please help me on this, thanks in advance.
Please suggest me solution with above code , I am new to javascript and unable to implement the solution in suggested link .
I have also used below code to create .XLSX file, Code is creating file but file is blank and showing an error message:
"The file Format and extension do not match.The file could be corrupted or unsafe......Do u want to opent it anyway"
var a = document.createElement('a');
var data_type = 'data:application/vnd.ms-excel';
var table_div = tab_text; //Your tab_text
var table_html = table_div.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
//setting the file name
a.download = 'exported_table.xlsx';
//triggering the function
a.click();
You can do like this:
window.saveAs(blob,filename);
function fnExcelReport(id, name) {
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'>";
var exportTable = $('#' + id).clone();
exportTable.find('input').each(function (index, elem) { $(elem).remove(); });
tab_text = tab_text + exportTable.html();
tab_text = tab_text + '</table></body></html>';
var fileName = name + '_' + parseInt(Math.random() * 10000000000) + '.xls';
//Save the file
var blob = new Blob([tab_text], { type: "application/vnd.ms-excel;charset=utf-8" })
window.saveAs(blob, fileName);
}`

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.

HTML table to Excel - format & extension don't match

I have a function that converts a HTML table into an Excel document. However upon the opening of the file, I receive the following message from Excel:
The file format and extension of 'something.xls' don't match. Etc etc...
Below is the function I am for the export, it is a slightly edited version of #SamPopes answer from this thread. The obj parameter is a table element I created using document.createElement('table');.
Is there any way to prevent this message upon opening the file?
function export(obj) {
var tab_text="<table border='2px'><tr>";
var textRange; var j=0;
tab = obj; //Table
for(j = 0 ; j < tab.rows.length ; j++){
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if you want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if you want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // removes input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"export.xls");
} else { //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
}
As I said in my comment above, here is the code for creating a CSV file. This works to avoid the error message you are receiving, but will eliminate any chance you have for formatting your data (As far as I know). Here is my code, which uses one process for IE and a second for all other browsers:
function exportTotalDataFile(){
var dataText = "";
var rowText = "";
'allData is generated through an AJAX call that creates a JSON'
'this loop creates the header row'
for (var index in allData[0]) {
rowText += index + ',';
}
'takes the trailing comma out, adds new row'
rowText = rowText.slice(0, -1);
dataText += rowText + '\r\n';
'Produces the data rows'
for (var i = 0; i < allData.length; i++) {
var rowText = "";
for (var index in allData[i]) {
rowText += '"' + allData[i][index] + '",';
}
rowText.slice(0, rowText.length - 1);
dataText += rowText + '\r\n';
}
var fileName = "Losses Report";
'Internet Explorer logic'
var isIE = false || !!document.documentMode;
if (isIE){
var IEwindow = window.open();
IEwindow.document.write('sep=,\r\n' + dataText);
IEwindow.document.close();
IEwindow.document.execCommand('SaveAs', true, fileName + ".csv");
IEwindow.close();
}
'All the other browsers'
else {
var uri = 'data:text/csv;charset=utf-8,' + escape(dataText);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
Sorry that this method is limited in the formatting department, but I hope this helps

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/

Categories

Resources