Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • How to export data to csv using javascript and jquery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.88k
    Comment on it

    Sometimes you face the problem to export the data into csv file using clientside platform. In this case you can use javascript and jquery.

    Below is the code to find out the solution:

    Javascript Code:

     $(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 = '"' + $ (i, row) {
                    var $row = $(row),
                        $cols = $row.find('td');
                    return $ (j, col) {
                        var $col = $(col),
                            text = $col.text();
                        return text.replace('"', '""'); // escape double quotes
                    .split(tmpColDelim).join(colDelim) + '"',
                // Data URI
                csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
                '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

    HTML Code:

    <div id="dvData">
                <th>Column One</th>
                <th>Column Two</th>
                <th>Column Three</th>
                <td>row1 Col1</td>
                <td>row1 Col2</td>
                <td>row1 Col3</td>
                <td>row2 Col1</td>
                <td>row2 Col2</td>
                <td>row2 Col3</td>
                <td>row3 Col1</td>
                <td>row3 Col2</td>
                <td>row3 Col3</td>
    <a href="#" class="export">Export Table data into Excel</a>

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: