How to data Export to CSV using JQuery or Javascri

2020-07-08 07:42发布

问题:

What I needed: We have value in the response.d that is comma deliminated value. Now I want to export the data of response.d to .csv file.

I have written this function to perform this. I have received the data in response.d but not exporting to the .csv file, so give the solution for this problem to export data in .csv file.

function BindSubDivCSV(){ 
  $.ajax({
      type: "POST", 
      url: "../../WebCodeService.asmx / ShowTrackSectorDepartureList", 
      data: "{}", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json",
      success: function (response) {  
        alert(response.d);//export to csv function needed here
      },
      error: function (data) {}
  });
  return false;
}

回答1:

In case you have no control over how the server-side works, here is a client-side solution that I have offered in another SO question, pending for that OP's acceptance: Export to CSV using jQuery and html

There are certain restrictions or limitations you will have to consider, as I have mentioned in my answer over there, which has more details.


This is the same demo I have offered: http://jsfiddle.net/terryyounghk/KPEGU/

And to give you a rough idea of what the script looks like.

What you need to change is how you iterate your data (in the other question's case it was table cells) to construct a valid CSV string. This should be trivial.

$(document).ready(function () {

    function exportTableToCSV($table, filename) {

        var $rows = $table.find('tr:has(td)'),

            // Temporary delimiter characters unlikely to be typed by keyboard
            // This is to avoid accidentally splitting the actual contents
            tmpColDelim = String.fromCharCode(11), // vertical tab character
            tmpRowDelim = String.fromCharCode(0), // null character

            // actual delimiter characters for CSV format
            colDelim = '","',
            rowDelim = '"\r\n"',

            // Grab text from table into CSV formatted string
            csv = '"' + $rows.map(function (i, row) {
                var $row = $(row),
                    $cols = $row.find('td');

                return $cols.map(function (j, col) {
                    var $col = $(col),
                        text = $col.text();

                    return text.replace('"', '""'); // escape double quotes

                }).get().join(tmpColDelim);

            }).get().join(tmpRowDelim)
                .split(tmpRowDelim).join(rowDelim)
                .split(tmpColDelim).join(colDelim) + '"',

            // Data URI
            csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

        $(this)
            .attr({
            'download': filename,
                'href': csvData,
                'target': '_blank'
        });
    }

    // This must be a hyperlink
    $(".export").on('click', function (event) {
        // CSV
        exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);

        // IF CSV, don't do event.preventDefault() or return false
        // We actually need this to be a typical hyperlink
    });
});


回答2:

Using the code above (from Terry Young) I found that in Opera it would refuse to give the file a name (simply calling it "download") and would not always work reliably.

To get it to work I had to create a binary blob:

    var filename = 'file.csv';
    var outputCSV = 'entry1,entry2,entry3';
    var blobby = new Blob([outputCSV], {type: 'text/plain'});

    $(exportLink).attr({
                'download' : filename,
                'href': window.URL.createObjectURL(blobby),
                'target': '_blank'
                });

    exportLink.click();

Also note that creating the "exportLink" variable on the fly would not work with Firefox so I had to have this in my HTML file:

    <div>
        <a id="exportLink"></a>
    </div>

Using the above I have successfully tested this using Windows 7 64bit and Opera (v22), Firefox (v29.0.1), and Chrome (v35.0.1916.153 m).

To enable similar functionality (albeit in a far less elegant manner) on Internet Explorer I had to use Downloadify.