dt1888 2013-03-03 19:50
浏览 47
已采纳

table2CSV.js - 工作很精彩,但在指定要导出的表时遇到问题

I'm having trouble exporting using table2CSV.js when there are multiple tables on the page.

The first one will work correctly, but any other buttons will export a blank file. Any ideas? If you need more info please advise.

I want to add that it's always the first table on the page that works correctly...

Please review single the call (JS):

function getCSVData(tableName){
    var csv_value=$(tableName).table2CSV({delivery:'value'});
    $("#csv_text").val(csv_value);
}

And the HTML form buttons to call the JS (there are a few on the page):

<form action="getCSV.php" method ="post" > 
    <input type="hidden" name="csv_text" id="csv_text">
    <input type="hidden" name="fileName" id="fileName" value="<?php echo($fileName); ?>">
    <input type="submit" value="Download Table 0" onclick="getCSVData('table#detail0')">
</form>


<form action="getCSV.php" method ="post" > 
    <input type="hidden" name="csv_text" id="csv_text">
    <input type="hidden" name="fileName" id="fileName" value="<?php echo($fileName); ?>">
    <input type="submit" value="Download Table 1" onclick="getCSVData('table#detail1')">
</form>

<form action="getCSV.php" method ="post" > 
    <input type="hidden" name="csv_text" id="csv_text">
    <input type="hidden" name="fileName" id="fileName" value="<?php echo($fileName); ?>">
    <input type="submit" value="Download Table 2" onclick="getCSVData('table#detail2')">
</form>

Here is a few table open tags for reference as well:

For reference, here's the getCSV.php file

<?php
    $file = $_REQUEST['fileName'];
    $filename = $file."_".date("Y-m-d_H-i",time());
    header("Content-type: application/vnd.ms-excel");
    header("Content-disposition: csv" . date("Y-m-d") . ".csv");
    header( "Content-disposition: filename=".$filename.".csv");

    $csv_output=stripcslashes($_REQUEST['csv_text']);
    print $csv_output;
    exit;   

?>

For reference, here's the table2CSV.js code:

jQuery.fn.table2CSV = function(options) {
    var options = jQuery.extend({
        separator: ',',
        header: [],
        delivery: 'popup' // popup, value
    },
    options);

    var csvData = [];
    var headerArr = [];
    var el = this;

    //header
    var numCols = options.header.length;
    var tmpRow = []; // construct header avalible array

    if (numCols > 0) {
        for (var i = 0; i < numCols; i++) {
            tmpRow[tmpRow.length] = formatData(options.header[i]);
        }
    } else {
        $(el).filter(':visible').find('th').each(function() {
            if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
        });
    }

    row2CSV(tmpRow);

    // actual data
    $(el).find('tr').each(function() {
        var tmpRow = [];
        $(this).filter(':visible').find('td').each(function() {
            if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
        });
        row2CSV(tmpRow);
    });
    if (options.delivery == 'popup') {
        var mydata = csvData.join('
');
        return popup(mydata);
    } else {
        var mydata = csvData.join('
');
        return mydata;
    }

    function row2CSV(tmpRow) {
        var tmp = tmpRow.join('') // to remove any blank rows
        // alert(tmp);
        if (tmpRow.length > 0 && tmp != '') {
            var mystr = tmpRow.join(options.separator);
            csvData[csvData.length] = mystr;
        }
    }
    function formatData(input) {
        // replace " with “
        var regexp = new RegExp(/["]/g);
        var output = input.replace(regexp, "“");
        //HTML
        var regexp = new RegExp(/\<[^\<]+\>/g);
        var output = output.replace(regexp, "");
        if (output == "") return '';
        return '"' + output + '"';
    }
    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;
    }
};
  • 写回答

1条回答 默认 最新

  • douxi5940 2013-03-04 00:36
    关注

    It is not working for the second and the third table because you give the same id to all your 3 inputs (hidden) in your forms.

    <input type="hidden" name="csv_text" id="csv_text">
    

    An ID should be UNIQUE

    If you have multiple HTMLElement with the same ID, when retrieve it in Javascript, it will retrieve the first found from the begining. So it will always retrieve the one from the first form.

    Change your inputs in each form for :

    <input type="hidden" name="csv_text" id="csv_text_1" />
    
    <input type="hidden" name="csv_text" id="csv_text_2" />
    
    <input type="hidden" name="csv_text" id="csv_text_3" />
    

    And then, modifiy your function:

    function getCSVData(tableName, num){
        var csv_value=$(tableName).table2CSV({delivery:'value'});
        $("#csv_text_" + num).val(csv_value);
    }
    

    Finally update your calls:

    <input type="submit" value="Download Table 0" onclick="getCSVData('table#detail0', '0')">
    
    <input type="submit" value="Download Table 0" onclick="getCSVData('table#detail1', '1')">
    
    <input type="submit" value="Download Table 0" onclick="getCSVData('table#detail2', '2')">
    

    Personnal opinion: It seems a little bit useless to send all the content of the table, just to add a file attachment header thanks to the PHP server. You are using the network to send a data that will be re-sent to you without any modification (just for header addition).

    If I have to do such a process, I would just send a simple GET request to a specific PHP script that will send me the correct header, and then, generate the CSV content, retrieving the data from the database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao