SoFunction
Updated on 2025-03-06

JS export table to excel compatible with both FF and IE examples


<pre name="code" class="html">Foreground call (the first parameter is the id of the table): <input value="export" type="button" />
function toExcel(inTblId, inWindow) {
if ($.) { //If it is IE browser
try {
var allStr = "";
var curStr = "";
if (inTblId != null && inTblId != "" && inTblId != "null") {
curStr = getTblData(inTblId, inWindow);
}
if (curStr != null) {
allStr += curStr;
}
else {
alert("The table you want to export does not exist!");
return;
}
var fileName = getExcelFileName();
doFileExport(fileName, allStr);
}
catch (e) {
alert("Exception occurred in export:" + + "->" + + "!");
}
}
else {
('data:application/-excel,' + encodeURIComponent($('div[id$=divGvData]').html()));
();
}
}
function getTblData(inTbl, inWindow) {
var rows = 0;
var tblDocument = document;
if (!!inWindow && inWindow != "") {
if (!(inWindow)) {
return null;
}
else {
tblDocument = eval(inWindow).document;
}
}
var curTbl = (inTbl);
if ( > 65000) {
alert('The number of source rows cannot be greater than 65000 rows');
return false;
}
if ( <= 1) {
alert('The data source has no data');
return false;
}
var outStr = "";
if (curTbl != null) {
for (var j = 0; j < ; j++) {
for (var i = 0; i < [j].; i++) {
if (i == 0 && rows > 0) {
outStr += " \t";
rows -= 1;
}
var tc = [j].cells[i];
if (j > 0 && () && () == "input") {
if (() == "checkbox") {
if ( == true) {
outStr += "Yes" + "\t";
}
else {
outStr += "No" + "\t";
}
}
}
else {

outStr += " "+[j].cells[i].innerText + "\t";
}
if ([j].cells[i].colSpan > 1) {
for (var k = 0; k < [j].cells[i].colSpan - 1; k++) {
outStr += " \t";
}
}
if (i == 0) {
if (rows == 0 && [j].cells[i].rowSpan > 1) {
rows = [j].cells[i].rowSpan - 1;
}
}
}
outStr += "\r\n";
}
}
else {
outStr = null;
alert(inTbl + "Not exist!");
}
return outStr;
}
function getExcelFileName() {
var d = new Date();
var curYear = ();
var curMonth = "" + (() + 1);
var curDate = "" + ();
var curHour = "" + ();
var curMinute = "" + ();
var curSecond = "" + ();
if ( == 1) {
curMonth = "0" + curMonth;
}
if ( == 1) {
curDate = "0" + curDate;
}
if ( == 1) {
curHour = "0" + curHour;
}
if ( == 1) {
curMinute = "0" + curMinute;
}
if ( == 1) {
curSecond = "0" + curSecond;
}
var fileName = "Device Status" + curYear + curMonth + curDate + curHour + curMinute + curSecond + ".xls";
return fileName;
}
function doFileExport(inName, inStr) {
var xlsWin = null;
if (!!("glbHideFrm")) {
xlsWin = glbHideFrm;
}
else {
var width = 1;
var height = 1;
var openPara = "left=" + ( / 2 + width / 2)
+ ",top=" + ( + height / 2)
+ ",scrollbars=no,width=" + width + ",height=" + height;
xlsWin = ("", "_blank", openPara);
}
(inStr);
();
('Saveas', true, inName);
();
} </pre>
<pre></pre>
<br>