I need to Export Data displayed in a Table to CSV Format. I have tried lot many things but couldn\'t get it working for IE 9 and above.
I have created a dummy fiddle
This will work on any browser, without the need of jQuery.
Add the following iframe anywhere in your page:
Give an id to the table in the page you want to export:
Customize your link or button to call the ExportToCsv function, passing the default file name and the id of table as parameters. For example: Add this to your JavaScript file or section:
function ExportToCsv(fileName, tableName) {
var data = GetCellValues(tableName);
var csv = ConvertToCsv(data);
if (navigator.userAgent.search("Trident") >= 0) {
window.CsvExpFrame.document.open("text/html", "replace");
window.CsvExpFrame.document.write(csv);
window.CsvExpFrame.document.close();
window.CsvExpFrame.focus();
window.CsvExpFrame.document.execCommand('SaveAs', true, fileName + ".csv");
} else {
var uri = "data:text/csv;charset=utf-8," + escape(csv);
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = fileName + ".csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
};
function GetCellValues(tableName) {
var table = document.getElementById(tableName);
var tableArray = [];
for (var r = 0, n = table.rows.length; r < n; r++) {
tableArray[r] = [];
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
var text = table.rows[r].cells[c].textContent || table.rows[r].cells[c].innerText;
tableArray[r][c] = text.trim();
}
}
return tableArray;
}
function ConvertToCsv(objArray) {
var array = typeof objArray != "object" ? JSON.parse(objArray) : objArray;
var str = "sep=,\r\n";
var line = "";
var index;
var value;
for (var i = 0; i < array.length; i++) {
line = "";
var array1 = array[i];
for (index in array1) {
if (array1.hasOwnProperty(index)) {
value = array1[index] + "";
line += "\"" + value.replace(/"/g, "\"\"") + "\",";
}
}
line = line.slice(0, -1);
str += line + "\r\n";
}
return str;
};
Click this to download a .csv
Name
Age
Email
Andrew
20
andrew@me.com
Bob
32
bob@me.com
Sarah
19
sarah@me.com
Anne
25
anne@me.com