2009-05-28 67 views
30

我正在使用jQuery表格到CSV插件。我更改了彈出窗口,以便它告訴瀏覽器下載CSV文件。jQuery表格到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)。

有關如何改善此問題的任何建議?

+4

的jQuery表到CSV插件:http://www.kunalbabre.com/projects/table2CSV.php,感謝注:Kunal Babre – timborden 2009-05-28 14:10:43

回答

20

研究發現,(從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']; 

?> 
+0

+1爲我工作。儘管如此,我最終使用了$(「body」)。append([enter-form-here]); – Eddie 2010-08-27 17:52:33

6

我不建議這樣「下載」CSV數據。 IE7只允許在地址欄中輸入2000個字符,因此文件被截斷的機率很高。

7

感謝您的問題和答案,對我很好。這裏是您的解決方案的(幾乎相同)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"]); 
} 
1

與所有瀏覽器不兼容,但沒有服務器端需要!請嘗試下面的代碼using 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(); 
});