我正在阅读这里所有类似的问题,但我无法使其正常工作,这是我最新的方法:
$(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
});
});
但是当我在Excel中打开它时,我一直遇到问题,因为字符,,é,í,ó,ú,ñ,没有正确显示,问题是如果我在记事本中打开文件我不会有这个问题,字符显示应该显示。
我也尝试过使用utf-8,utf-16等等:utf-8,%EF%BB%BF
我做错了什么?