繁体   English   中英

jQuery表到CSV导出

[英]jQuery Table to CSV export

我正在使用jQuery Table to CSV Plugin。 我已经更改了弹出窗口,以便它告诉浏览器下载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'];

?>

谢谢你的问题和答案,对我来说效果很好。 这是我正在使用的解决方案的(几乎相同的)ASP.Net版本:

将table2CSV.js弹出功能更改为:

function popup(data) {
       $("body").append('<form id="exportform" action="CsvExport.ashx" method="post" target="_blank"><input type="hidden" id="exportdata" name="exportdata" /></form>');
       $("#exportdata").val(data);
       $("#exportform").submit().remove();
       return true;
} 

注意到从export.php到.ashx泛型处理程序的更改。

通用处理程序代码:

 public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "application/force-download";
    context.Response.AddHeader("content-disposition", "filename=filename.csv");

    context.Response.Write(context.Request.Form["exportdata"]);
}

我不建议以这种方式“下载”CSV数据。 IE7在地址栏中最多只允许2000个字符,因此文件被截断的可能性很高。

与所有浏览器不兼容,但不需要服务器端! 使用JSFiddle尝试下面的代码,并告诉我们它是否在您的浏览器中运行。

$('<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();
});

我强烈推荐使用http://datatables.net/extras/tabletools/ ,它很容易玩桌子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM