javascript - jQuery 表到 CSV 导出

标签 javascript jquery

我正在使用 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/

相关文章:

jquery - reactjs - 在 react 树之外公开 react 组件方法

javascript - 带有谷歌地图事件监听器的类方法运行外部函数

javascript - MVC 使用参数从 View 重定向到 Controller

javascript - 这在 Mozilla : "let blocks and let expressions are obsolete" 中意味着什么

javascript - 突出显示文本并更改颜色

javascript - 无法从 kendotreelist 中的 kendo 模板调用 typescript 中的函数

javascript - 将选择框文本插入数据库

javascript - 如何修复元素的外观?

javascript - AWS S3 - 凭据在代码中公开

javascript - 在 javascript 中创建就绪时调用函数