I was reading all of the similar questions in here, but I can't make it work right, this was my latest approach:
$(document).ready(function () {
function exportTableToCSV($table, filename) {
var $headers = $table.find('tr:has(th)')
,$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
var csv = '"';
csv += formatRows($headers.map(grabRow));
csv += rowDelim;
csv += formatRows($rows.map(grabRow)) + '"';
textEncoder = new TextEncoder('windows-1252');
var csvContentEncoded = textEncoder.encode([csv]);
var csvData = new Blob([csvContentEncoded], { type: 'text/csv;charset=windows-1252;' });
var csvUrl = URL.createObjectURL(csvData);
// Format the output so it has the appropriate delimiters
function formatRows(rows){
return rows.get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim);
}
// Grab and format a row from the table
function grabRow(i,row){
var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th') won't work...
var $cols = $row.find('td');
if(!$cols.length) $cols = $row.find('th');
return $cols.map(grabCol)
.get().join(tmpColDelim);
}
// Grab and format a column from the table
function grabCol(j,col){
var $col = $(col),
$text = $col.text();
return $text.replace('"', '""'); // escape double quotes
}
}
// This must be a hyperlink
$("#export").click(function (event) {
// var outputFile = 'export'
var outputFile = window.prompt("Nombre deseado del reporte: ") || 'export';
outputFile = outputFile.replace('.csv','') + '.csv'
// CSV
exportTableToCSV.apply(this, [$('#tablareporte > table'), outputFile]);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
But I keep having problems when I open it in Excel, because characters as, á,é,í,ó,ú,ñ, doesn't show correctly, the thing is if I open the file in notepad I don't have this problem, characters show as supposed to show.
I also tried with utf-8, utf-16 and something like this: utf-8,%EF%BB%BF
What am I doing wrong?