我正在使用 jQuery Table to CSV 插件。我更改了弹出窗口,以便它告诉浏览器下载 CSV 文件。
它是:
function popup(data) {
var generator = window.open('', 'csv', 'height=400,width=600');
generator.document.write('<html><head><title>CSV</title>');
generator.document.write('</head><body >');
generator.document.write('<textArea cols=70 rows=15 wrap="off" >');
generator.document.write(data);
generator.document.write('</textArea>');
generator.document.write('</body></html>');
generator.document.close();
return true;
}
我已将其更改为:
function popup(data) {
window.location='data:text/csv;charset=utf8,' + encodeURIComponent(data);
return true;
}
在大多数情况下,它是有效的。它仍然需要您找到您的电子表格软件,并创建您自己的文件名...因为它会创建一个奇怪的文件名(例如:14YuskG_.csv.part)。
有什么改进建议吗?
最佳答案
找到了一个可行的解决方案(在 http://www.topsemtips.com/2008/11/save-html-table-to-excel-using-jquery/ 的帮助下):
我将函数更改为:
function popup(data) {
$("#main div.inner").append('<form id="exportform" action="export.php" method="post" target="_blank"><input type="hidden" id="exportdata" name="exportdata" /></form>');
$("#exportdata").val(data);
$("#exportform").submit().remove();
return true;
}
并创建文件 export.php:
<?php
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: filename=export.csv");
header("Pragma: no-cache");
header("Expires: 0");
print $_REQUEST['exportdata'];
?>
更新: 对 IE7 更友好的版本:
<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=filename.csv');
print $_POST['exportdata'];
?>
关于javascript - jQuery 表到 CSV 导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/921037/