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

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/

Related

Html tables within div export to excel

<script type="text/javascript">
$(document).ready(function () {
//getting values of current time for generating the file name
$(".toExcelButton").click(function(){
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();
})
});
</script>
Need to export div tables to excel. The above code works fine in Chrome but not working in IE. Can anyone help me out on the same.
In IE a dynamically created anchor tag needs to be added to the DOM to execute its click event. Furthermore the download attribute is not supported in the IE:
Download attribute on A tag not working in IE
Edit:
Recently I posted many answers handling this issue, here are two of those:
image does not download with it's own extension
JS Base64 string to downloadable pdf - Edge
Basically you have to use msSaveOrOpenBlob() in IE:
var tF = 'Whatever.xls';
var tB = new Blob(..);
if(window.top.navigator.msSaveOrOpenBlob){
//Store Blob in IE
window.top.navigator.msSaveOrOpenBlob(tB, tF)
}
else{
//Store Blob in others
var tA = document.body.appendChild(document.createElement('a'));
tA.href = URL.createObjectURL(tB);
tA.download = tF;
tA.style.display = 'none';
tA.click();
tA.parentNode.removeChild(tA)
}
In the case above:
var tT = new XMLSerializer().serializeToString(document.querySelector('table')); //Serialised table
var tF = 'Whatever.xls'; //Filename
var tB = new Blob([tT]); //Blob
if(window.top.navigator.msSaveOrOpenBlob){
//Store Blob in IE
window.top.navigator.msSaveOrOpenBlob(tB, tF)
}
else{
//Store Blob in others
var tA = document.body.appendChild(document.createElement('a'));
tA.href = URL.createObjectURL(tB);
tA.download = tF;
tA.style.display = 'none';
tA.click();
tA.parentNode.removeChild(tA)
}
https://jsfiddle.net/23ao1v0s/1/
Please check the below given link. I think you will get a solution for your question
https://github.com/rainabba/jquery-table2excel

Angular download csv file international characters

Hi I am generating a CSV file based on some filtered data in my angular web app.
The input I am sending to my csvString is:
Torup Bakkegård (Middelfartvej 105); Coop Brøndby; (Holkebjergvej 54);
The output is always ruined once i open the excel file:
TorupBakkegård(Middelfartvej105) CoopBrøndby(Holkebjergvej54)
However when I open it with notepad it's fine, so it's just MS Excel(using the latest version) that seems to ruin it.
TorupBakkegård(Middelfartvej105);CoopBrøndby(Holkebjergvej54);
I tried with several encodings, it seems excel simply does not care
Here is the code javascript:
vm.downloadExcel = function (bookings) {
var csvRows = [];
var csvHeading = "Afhentningsadresse;Modtager";
csvRows.push(csvHeading + "\n");
for (var i = 0; i < bookings.length; i++) {
var csvRow = "";
csvRow += bookings[i].pickupAddress + ";";
csvRow += bookings[i].customerAddress + ";";
csvRows.push(csvRow + "\n");
}
var csvString = csvRows.join("%0A");
var a = document.createElement('a');
a.href = 'data:application/csv;charset=Windows-1252,' + csvString;
a.target = '_blank';
a.download = 'myFile.csv';
console.log(a.href);
document.body.appendChild(a);
a.click();
After a bit of research we figured out that we didn't mention the BOM.
The BOM is responsible for the encoding in the actual file.
So after changing:
a.href = 'data:application/csv;charset=Windows-1252,' + csvString;
With:
a.href = 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURI(csvString);
Everything works just fine.
Credits goes to: Gergő Nagy, for answering:
Javascript to csv export encoding issue

HTML --> Excel file. Include vba code in downloaded file?

I currently have a block of code that exports tables in my HTML body to one excel file.
$(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.getElementsByClassName("dvData");
var table_html = table_div[0].outerHTML.replace(/ /g, '%20');
var table_html2 = table_div[1].outerHTML.replace(/ /g, '%20');
var table_html3 = table_div[2].outerHTML.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html + "<br></br>" + table_html2 + "<br></br>" + table_html3;
//setting the file name
a.download = 'exported_table_' + postfix + '.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
});
});
</script>
When the excel file opens, I want it to have some vba code that automatically runs when the user opens the downloaded file.
Is this possible? If so, how do I "embed" the vba code into the excel file my code exports?

Javascript How to SetTimeOut while getting a list of files with Scripting.FileSystemObject

This code is for internal, offline, single user use, IE only. The code looks at a folder, and lists all files including those in subfolders. It sorts through the data based on some date fields and datelastmodified. It also uses and if to throw out thumbs.db entries. All of the data is put into a table.
My issue is that this script can take a long time to get the data. I would like to add a progress bar but the progress bar cant update while the script is running. After some research it looks like SetTimeOut can allow the page elements to be updated as the script runs, therefore allowing the progress bar to work and looking overall cleaner. However I can not figure out of to implement SetTimeOut into my existing code.
<script type="text/javascript">
var fso = new ActiveXObject("Scripting.FileSystemObject");
function ShowFolderFileList(folderspec) {
var beginningdate = new Date(startdate.value);
var finishdate = new Date(enddate.value);
var s = "";
var f = fso.GetFolder(folderspec);
var subfolders = new Enumerator(f.SubFolders);
for (subfolders.moveFirst(); !subfolders.atEnd(); subfolders.moveNext()) {
s += ShowFolderFileList(subfolders.item().path);
}
// display all file path names.
var fc = new Enumerator(f.files);
for (i = 0; !fc.atEnd(); fc.moveNext()) {
if (fc.item().name != "Thumbs.db") {
var dateModified = fc.item().DatelastModified;
if (dateModified >= beginningdate && dateModified <= finishdate) {
Date.prototype.toDateString = function () {
return [this.getMonth() + 1, '/', this.getDate(), '/', this.getFullYear()].join('');
}
var dateModifiedClean = (new Date(fc.item().DatelastModified).toDateString());
s += "<table border=0 width=100% cellspacing=0><tr " + ((i % 2) ? "" : "bgcolor=#EBF1DE") + "><td width=75%><font class=find><b>" + fc.item().ParentFolder.name + "</b>" + " - " + fc.item().name + "</font></td><td width=25% align=right><font class=find>" + dateModifiedClean + "</font></td></tr>";
i++;
}
}
}
var results = s + "</table>";
return results;
}
function listFiles() {
outPut.innerHTML = ShowFolderFileList('*Path to scan*');
}
</script>
outPut is the ID of a div tag where the results table is displayed. A button calls the listfiles function.

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();
}
})();

Categories

Resources