How can I convert multiple html tables to an excel sheet with multiple worksheets? Could you please help into this.
My example https://jsfiddle.net/kdkd/5p22gdag/>
Bhutani Vijay's code works perfectly fine. For IE 11 compatibility I used the Blob object as below:
var tablesToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,',
tmplWorkbookXML = '' +
'Axel Richter {created} ' +
'' +
'' +
'' +
' ' +
'{worksheets} ',
tmplWorksheetXML = '{rows}
',
tmplCellXML = '{data} | ',
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(tables, wsnames, wbname, appname) {
var ctx = "";
var workbookXML = "";
var worksheetsXML = "";
var rowsXML = "";
for (var i = 0; i < tables.length; i++) {
if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
for (var j = 0; j < tables[i].rows.length; j++) {
rowsXML += ''
for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
dataValue = (dataValue) ? dataValue : tables[i].rows[j].cells[k].innerHTML;
var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
dataFormula = (dataFormula) ? dataFormula : (appname == 'Calc' && dataType == 'DateTime') ? dataValue : null;
ctx = {
attributeStyleID: (dataStyle == 'Currency' || dataStyle == 'Date') ? ' ss:StyleID="' + dataStyle + '"' : '',
nameType: (dataType == 'Number' || dataType == 'DateTime' || dataType == 'Boolean' || dataType == 'Error') ? dataType : 'String',
data: (dataFormula) ? '' : dataValue,
attributeFormula: (dataFormula) ? ' ss:Formula="' + dataFormula + '"' : ''
};
rowsXML += format(tmplCellXML, ctx);
}
rowsXML += '
'
}
ctx = {
rows: rowsXML,
nameWS: wsnames[i] || 'Sheet' + i
};
worksheetsXML += format(tmplWorksheetXML, ctx);
rowsXML = "";
}
ctx = {
created: (new Date()).getTime(),
worksheets: worksheetsXML
};
workbookXML = format(tmplWorkbookXML, ctx);
var link = document.createElement("A");
// IE 11
if (window.navigator.msSaveBlob) {
var blob = new Blob([workbookXML], {
type: "application/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, 'test.xls');
}
// Chrome and other browsers
else {
link.href = uri + base64(workbookXML);
}
link.download = wbname || 'Workbook.xls';
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
})();