Export to CSV in Jquery

Export to CSV using jQuery and HTML

Demo

See below for an explanation.

$(document).ready(function() {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard // This is to avoid accidentally splitting the actual contents tmpColDelim = String.fromCharCode(11), // vertical tab character tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format colDelim = '","', rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string csv = '"' + $rows.map(function(i, row) { var $row = $(row), $cols = $row.find('td');
return $cols.map(function(j, col) { var $col = $(col), text = $col.text();
return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim) .split(tmpRowDelim).join(rowDelim) .split(tmpColDelim).join(colDelim) + '"';
// Deliberate 'false', see comment below if (false && window.navigator.msSaveBlob) {
var blob = new Blob([decodeURIComponent(csv)], { type: 'text/csv;charset=utf8' });
// Crashes in IE 10, IE 11 and Microsoft Edge // See MS Edge Issue #10396033 // Hence, the deliberate 'false' // This is here just for completeness // Remove the 'false' at your own risk window.navigator.msSaveBlob(blob, filename);
} else if (window.Blob && window.URL) { // HTML5 Blob var blob = new Blob([csv], { type: 'text/csv;charset=utf-8' }); var csvUrl = URL.createObjectURL(blob);
$(this) .attr({ 'download': filename, 'href': csvUrl }); } else { // Data URI var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this) .attr({ 'download': filename, 'href': csvData, 'target': '_blank' }); } }
// This must be a hyperlink $(".export").on('click', function(event) { // CSV var args = [$('#dvData>table'), 'export.csv'];
exportTableToCSV.apply(this, args);
// If CSV, don't do event.preventDefault() or return false // We actually need this to be a typical hyperlink });});
a.export,a.export:visited {  display: inline-block;  text-decoration: none;  color: #000;  background-color: #ddd;  border: 1px solid #ccc;  padding: 8px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><a href="#" class="export">Export Table data into Excel</a><div id="dvData">  <table>    <tr>      <th>Column One</th>      <th>Column Two</th>      <th>Column Three</th>    </tr>    <tr>      <td>row1 Col1</td>      <td>row1 Col2</td>      <td>row1 Col3</td>    </tr>    <tr>      <td>row2 Col1</td>      <td>row2 Col2</td>      <td>row2 Col3</td>    </tr>    <tr>      <td>row3 Col1</td>      <td>row3 Col2</td>      <td>row3 Col3</td>    </tr>    <tr>      <td>row4 'Col1'</td>      <td>row4 'Col2'</td>      <td>row4 'Col3'</td>    </tr>    <tr>      <td>row5 "Col1"</td>      <td>row5 "Col2"</td>      <td>row5 "Col3"</td>    </tr>    <tr>      <td>row6 "Col1"</td>      <td>row6 "Col2"</td>      <td>row6 "Col3"</td>    </tr>  </table></div>

Export to csv in jQuery

You can do that in the client side only, in browser that accept Data URIs:

data:application/csv;charset=utf-8,content_encoded_as_url

In your example the Data URI must be:

data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333

You can call this URI by:

  • using window.open
  • or setting the window.location
  • or by the href of an anchor
  • by adding the download attribute it will work in chrome, still have to test in IE.

To test, simply copy the URIs above and paste in your browser address bar. Or test the anchor below in a HTML page:

<a download="somedata.csv" href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333">Example</a>

To create the content, getting the values from the table, you can use table2CSV and do:

var data = $table.table2CSV({delivery:'value'});

$('<a></a>')
.attr('id','downloadFile')
.attr('href','data:text/csv;charset=utf8,' + encodeURIComponent(data))
.attr('download','filename.csv')
.appendTo('body');

$('#downloadFile').ready(function() {
$('#downloadFile').get(0).click();
});

Most, if not all, versions of IE don't support navigation to a data link, so a hack must be implemented, often with an iframe. Using an iFrame combined with document.execCommand('SaveAs'..), you can get similar behavior on most currently used versions of IE.

How to export data from table to csv file using jquery

CSV format cannot accept $('.dataTable').html() as .html() is not a structured data, it's not even data, just a silly hmtl.

You have to get data from your table, make a string representing CSV format, and download it, As you don't show your table data structure here's working demo below

$('#export').click(function() {  var titles = [];  var data = [];
/* * Get the table headers, this will be CSV headers * The count of headers will be CSV string separator */ $('.dataTable th').each(function() { titles.push($(this).text()); });
/* * Get the actual data, this will contain all the data, in 1 array */ $('.dataTable td').each(function() { data.push($(this).text()); }); /* * Convert our data to CSV string */ var CSVString = prepCSVRow(titles, titles.length, ''); CSVString = prepCSVRow(data, titles.length, CSVString);
/* * Make CSV downloadable */ var downloadLink = document.createElement("a"); var blob = new Blob(["\ufeff", CSVString]); var url = URL.createObjectURL(blob); downloadLink.href = url; downloadLink.download = "data.csv";
/* * Actually download CSV */ document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink);});
/** Convert data array to CSV string* @param arr {Array} - the actual data* @param columnCount {Number} - the amount to split the data into columns* @param initial {String} - initial string to append to CSV string* return {String} - ready CSV string*/function prepCSVRow(arr, columnCount, initial) { var row = ''; // this will hold data var delimeter = ','; // data slice separator, in excel it's `;`, in usual CSv it's `,` var newLine = '\r\n'; // newline separator for CSV row
/* * Convert [1,2,3,4] into [[1,2], [3,4]] while count is 2 * @param _arr {Array} - the actual array to split * @param _count {Number} - the amount to split * return {Array} - splitted array */ function splitArray(_arr, _count) { var splitted = []; var result = []; _arr.forEach(function(item, idx) { if ((idx + 1) % _count === 0) { splitted.push(item); result.push(splitted); splitted = []; } else { splitted.push(item); } }); return result; } var plainArr = splitArray(arr, columnCount); // don't know how to explain this // you just have to like follow the code // and you understand, it's pretty simple // it converts `['a', 'b', 'c']` to `a,b,c` string plainArr.forEach(function(arrItem) { arrItem.forEach(function(item, idx) { row += item + ((idx + 1) === arrItem.length ? '' : delimeter); }); row += newLine; }); return initial + row;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="export">export</button>
<table class="dataTable"> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td>Alfreds Futterkiste</td> <td>Maria Anders</td> <td>Germany</td> </tr> <tr> <td>Centro comercial Moctezuma</td> <td>Francisco Chang</td> <td>Mexico</td> </tr> <tr> <td>Ernst Handel</td> <td>Roland Mendel</td> <td>Austria</td> </tr> <tr> <td>Island Trading</td> <td>Helen Bennett</td> <td>UK</td> </tr> <tr> <td>Laughing Bacchus Winecellars</td> <td>Yoshi Tannamuri</td> <td>Canada</td> </tr> <tr> <td>Magazzini Alimentari Riuniti</td> <td>Giovanni Rovelli</td> <td>Italy</td> </tr></table>

How to export data to CSV using Javascript?

Assuming the data argument contains an array of objects which you use to build the CSV data, you can use Object.keys() and Object.value() to dynamically build the data. Using this method it does not matter what the key names are, or how many of them is contained in the data.

function download_csv(data, sensor) {  let csvHeader = Object.keys(data[0]).join(',') + '\n'; // header row  let csvBody = data.map(row => Object.values(row).join(',')).join('\n');
var hiddenElement = document.createElement('a'); hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvHeader + csvBody); hiddenElement.target = '_blank'; hiddenElement.download = sensor + '.csv'; hiddenElement.click();}
let data = [{ lorem: 'ipsum', foo: 'bar', fizz: 'buzz'}];download_csv(data, 'foobar');

Javascript/ jQuery : Exporting data in CSV not working in IE

After using Javascript it will solve your problem.

Use this for IE,

var IEwindow = window.open();
IEwindow.document.write('sep=,\r\n' + CSV);
IEwindow.document.close();
IEwindow.document.execCommand('SaveAs', true, fileName + ".csv");
IEwindow.close();

For more information i have written tutorial on that, see - Download JSON data in CSV format Cross Browser Support

Hope this will be helpful for you.

How to export search criteria to excel/csv in Jquery Datatable

I hope this will help the others too.

  1. save text of selected officeId
  2. save text of selected departemenId
  3. save value from datatables search input
  4. use cusomize option for each button
  5. [easy because this is only text] for csvhtml5 we only need "\n" as ENTER new row, then add them before created dt CSV element
  6. [hard because this is OFFICE XML] for excelhtml5 we need to add OFFICE XML before created dt XML element. The hard point is we need to know first what is OFFICE XML and how to create OFFICE XML manually

here we goes

replace

buttons: [
{
extend: 'excelHtml5',
filename:'EmployeeList'
},
{
extend: 'csvHtml5',
filename:'EmployeeList'
}
]

into this

buttons: [ 
{
extend: 'csvHtml5',
filename:'EmployeeList',
customize: function( csv ) {
var office = $('#officeId :selected').text();
var department = $('#officeId :selected').text();
var search = $('.dataTables_filter input').val();
return "Office: "+ office +"\n"+"Department: "+department+"\n"+"Search Keyword: "+search+"\n\n"+ csv;
}
},
{
extend: 'excelHtml5',
filename:'EmployeeList',
customize: function( xlsx ) {
var office = $('#officeId :selected').text();
var department = $('#officeId :selected').text();
var search = $('.dataTables_filter input').val();
var search = $('.dataTables_filter input').val();
var sheet = xlsx.xl.worksheets['sheet1.xml'];
var downrows = 4; //number of rows for heading
var clRow = $('row', sheet);
//update Row
clRow.each(function () {
var attr = $(this).attr('r');
var ind = parseInt(attr);
ind = ind + downrows;
$(this).attr("r",ind);
});

// Update row > c
$('row c ', sheet).each(function () {
var attr = $(this).attr('r');
var pre = attr.substring(0, 1);
var ind = parseInt(attr.substring(1, attr.length));
ind = ind + downrows;
$(this).attr("r", pre + ind);
});

function Addrow(index,data) {
msg='<row r="'+index+'">'
for(i=0;i<data.length;i++){
var key=data[i].k;
var value=data[i].v;
msg += '<c t="inlineStr" r="' + key + index + '" s="0">';
msg += '<is>';
msg += '<t>'+value+'</t>';
msg+= '</is>';
msg+='</c>';
}
msg += '</row>';
return msg;
}

//insert
var newline = Addrow(1, [{ k: 'A', v: 'Office: ' + office}]);
newline += Addrow(2, [{ k: 'A', v: 'Department: ' + department}]);
newline += Addrow(3, [{ k: 'A', v: 'Search Keyword: ' + search}]);

sheet.childNodes[0].childNodes[1].innerHTML = newline + sheet.childNodes[0].childNodes[1].innerHTML;
}
}
]

DEMO : https://output.jsbin.com/teyupav

PASTEBIN : http://pastebin.com/ZGt61DCT

Thanks to AugustLEE, J e Harms (member) and Alan (site admin) from datatables.net forum

REFERENCE:

https://datatables.net/extensions/buttons/examples/initialisation/export.html

https://datatables.net/reference/button/excelHtml5

https://datatables.net/reference/api/buttons.exportData()

CSV export

https://datatables.net/forums/discussion/38275

EXCELHTML5 export

https://datatables.net/forums/discussion/39707

https://datatables.net/forums/discussion/36045/excel-export-add-rows-and-data

UPDATE 1: Fix innerHTML problem from safari and IE8 below

this fix is reference from Raghul in same datatables thread https://datatables.net//forums/discussion/comment/103911/#Comment_103911

REPLACE

function Addrow(index,data) {
msg='<row r="'+index+'">'
for(i=0;i<data.length;i++){
var key=data[i].k;
var value=data[i].v;
msg += '<c t="inlineStr" r="' + key + index + '" s="0">';
msg += '<is>';
msg += '<t>'+value+'</t>';
msg+= '</is>';
msg+='</c>';
}
msg += '</row>';
return msg;
}

//insert
var newline = Addrow(1, [{ k: 'A', v: 'Office: ' + office}]);
newline += Addrow(2, [{ k: 'A', v: 'Department: ' + department}]);
newline += Addrow(3, [{ k: 'A', v: 'Search Keyword: ' + search}]);

sheet.childNodes[0].childNodes[1].innerHTML = newline + sheet.childNodes[0].childNodes[1].innerHTML;

INTO

function Addrow(index, data) {
var row = sheet.createElement('row');
row.setAttribute("r", index);
for (i = 0; i < data.length; i++) {
var key = data[i].key;
var value = data[i].value;

var c = sheet.createElement('c');
c.setAttribute("t", "inlineStr");
c.setAttribute("s", "0");
c.setAttribute("r", key + index);

var is = sheet.createElement('is');
var t = sheet.createElement('t');
var text = sheet.createTextNode(value)

t.appendChild(text);
is.appendChild(t);
c.appendChild(is);

row.appendChild(c);
}

return row;
}

var r1 = Addrow(1, [{ key: 'A', value: 'Office: ' + office }]);
var r2 = Addrow(2, [{ key: 'A', value: 'Department: ' + department }]);
var r3 = Addrow(3, [{ key: 'A', value: 'Search Keyword: ' + search }]);
var r4 = Addrow(4, [{ key: 'A', value: '' }]);

var sheetData = sheet.getElementsByTagName('sheetData')[0];

sheetData.insertBefore(r4,sheetData.childNodes[0]);
sheetData.insertBefore(r3,sheetData.childNodes[0]);
sheetData.insertBefore(r2,sheetData.childNodes[0]);
sheetData.insertBefore(r1,sheetData.childNodes[0]);

DEMO: https://output.jsbin.com/kevosub/

How to export JavaScript array info to csv (on client side)?

You can do this in native JavaScript. You'll have to parse your data into correct CSV format as so (assuming you are using an array of arrays for your data as you have described in the question):

const rows = [
["name1", "city1", "some other info"],
["name2", "city2", "more info"]
];

let csvContent = "data:text/csv;charset=utf-8,";

rows.forEach(function(rowArray) {
let row = rowArray.join(",");
csvContent += row + "\r\n";
});

or the shorter way (using arrow functions):

const rows = [
["name1", "city1", "some other info"],
["name2", "city2", "more info"]
];

let csvContent = "data:text/csv;charset=utf-8,"
+ rows.map(e => e.join(",")).join("\n");

Then you can use JavaScript's window.open and encodeURI functions to download the CSV file like so:

var encodedUri = encodeURI(csvContent);
window.open(encodedUri);

Edit:

If you want to give your file a specific name, you have to do things a little differently since this is not supported accessing a data URI using the window.open method. In order to achieve this, you can create a hidden <a> DOM node and set its download attribute as follows:

var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF

link.click(); // This will download the data file named "my_data.csv".


Related Topics



Leave a reply



Submit