1

I'm trying to figure out how to export a table that has to be a little more complex than the examples I can find. Here is my code and I'd like to be able to export a clean csv of only the table content. Currently I get a csv file but the data isn't formatted great. the lines r/n/ part doesn't seem to be working as I would expect. Here is my code if

index.html

<!DOCTYPE>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">


        <title>Exporting Data to a CSV File</title>


        <link rel="stylesheet" type="text/css" href="main.css">
    </head>

    <body>
        <div class='container' id="dvData"> 
            <table class="table table-striped table-condensed default_datatable dataTable" id="ob_details">
                <thead>
                    <tr role="row">
                        <th class="natural sorting_asc" role="columnheader" tabindex="0" aria-controls="ob_details" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Date: activate to sort column descending" style="width: 0px;">Date
                            <i class="fa fa-caret-up fa-lg"></i>
                        </th>
                        <th class="numeric sorting" role="columnheader" tabindex="0" aria-controls="ob_details" rowspan="1" colspan="1" aria-label="Impressions: activate to sort column ascending" style="width: 0px;">Impressions
                            <i class="fa fa-caret-up fa-lg"></i>
                        </th>
                        <th class="numeric sorting" role="columnheader" tabindex="0" aria-controls="ob_details" rowspan="1" colspan="1" aria-label="Clicks: activate to sort column ascending" style="width: 0px;">Clicks
                            <i class="fa fa-caret-up fa-lg"></i>
                        </th>
                        <th class="currency sorting" role="columnheader" tabindex="0" aria-controls="ob_details" rowspan="1" colspan="1" aria-label="Total: activate to sort column ascending" style="width: 0px;">Total
                            <i class="fa fa-caret-up fa-lg"></i>
                        </th>
                    </tr>
                </thead>
<!--
                <tfoot>
                    <tr>
                        <th rowspan="1" colspan="1">Totals
                            <i class="fa fa-caret-up fa-lg"></i>
                        </th>
                        <th rowspan="1" colspan="1">9945
                            <i class="fa fa-caret-up fa-lg"></i>
                        </th>
                        <th rowspan="1" colspan="1">1122
                            <i class="fa fa-caret-up fa-lg"></i>
                        </th>
                        <th rowspan="1" colspan="1">$156.20
                            <i class="fa fa-caret-up fa-lg"></i>
                        </th>
                    </tr>
                </tfoot>
-->
                <tbody role="alert" aria-live="polite" aria-relevant="all">
                    <tr class="odd">
                        <td class=" sorting_1">2015-08-26</td>

                        <td class=" ">1887</td>

                        <td class=" ">207</td>

                        <td class=" ">$28.07</td>

                      </tr><tr class="even">
                        <td class=" sorting_1">2015-08-27</td>

                        <td class=" ">1974</td>

                        <td class=" ">206</td>

                        <td class=" ">$33.80</td>

                      </tr><tr class="odd">
                        <td class=" sorting_1">2015-08-28</td>

                        <td class=" ">1497</td>

                        <td class=" ">159</td>

                        <td class=" ">$26.26</td>

                      </tr><tr class="even">
                        <td class=" sorting_1">2015-08-29</td>

                        <td class=" ">926</td>

                        <td class=" ">107</td>

                        <td class=" ">$18.50</td>

                      </tr><tr class="odd">
                        <td class=" sorting_1">2015-08-30</td>

                        <td class=" ">1188</td>

                        <td class=" ">154</td>

                        <td class=" ">$18.21</td>

                      </tr><tr class="even">
                        <td class=" sorting_1">2015-08-31</td>

                        <td class=" ">1598</td>

                        <td class=" ">182</td>

                        <td class=" ">$31.36</td>

                      </tr><tr class="odd">
                        <td class=" sorting_1">2015-09-01</td>

                        <td class=" ">875</td>

                        <td class=" ">107</td>

                        <td class=" ">$0.00</td>

                      </tr><tr class="even">
                        <td class=" sorting_1">Date</td>

                        <td class=" ">0</td>

                        <td class=" ">0</td>

                        <td class=" ">$0.00</td>
                    </tr>
                </tbody>
            </table>
        </div>

            <br/>
            <div class='button'>
                <a href="#" id ="export" role='button'>CSV File</a>
            </div>

        <!-- Scripts -->
        <script type='text/javascript' src='https://code.jquery.com/jquery-1.11.0.min.js'></script>
        <!-- If you want to use jquery 2+: https://code.jquery.com/jquery-2.1.0.min.js -->
        <script type="text/javascript" src="html2csv.js"></script>
    </body>
</html>

html2csv.js

$(document).ready(function () {
    console.log("HELLO")
    function exportTableToCSV($table, filename) {
        var $headers = $table.find('thead:has(tr):has(th)')
            ,$rows = $table.find('tbody:has(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
            var csv = '"';
            csv += formatRows($headers.map(grabRow));
            csv += rowDelim;
            csv += formatRows($rows.map(grabRow)) + '"';
            // Data URI
            var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
        $(this)
            .attr({
            'download': filename
                ,'href': csvData
                //,'target' : '_blank' //if you want it to open in a new window
        });
        //------------------------------------------------------------
        // Helper Functions 
        //------------------------------------------------------------
        // Format the output so it has the appropriate delimiters
        function formatRows(rows){
            return rows.get().join(tmpRowDelim)
                .split(tmpRowDelim).join(rowDelim)
                .split(tmpColDelim).join(colDelim);
        }
        // Grab and format a row from the table
        function grabRow(i,row){

            var $row = $(row);
            //for some reason $cols = $row.find('td') || $row.find('th') won't work...
            var $cols = $row.find('td'); 
            if(!$cols.length) $cols = $row.find('th');  
            return $cols.map(grabCol)
                        .get().join(tmpColDelim);
        }
        // Grab and format a column from the table 
        function grabCol(j,col){
            var $col = $(col),
                $text = $col.text().trim();
            return $text.replace('"', '""'); // escape double quotes
        }
    }
    // This must be a hyperlink
    $("#export").click(function (event) {
        // var outputFile = 'export'
        var outputFile = window.prompt("What do you want to name your output file (Note: This won't have any effect on Safari)") || 'export';
        outputFile = outputFile.replace('.csv','') + '.csv'

        // CSV
        exportTableToCSV.apply(this, [$('#dvData>table'), outputFile]);

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

no, my problem is that I have it exporting the csv but it only formats the top row. then the rest is just data explosion.

here is an example

"Date","Impressions","Clicks","Total"
"2015-08-26","1887","207","$28.07","2015-08-27","1974","206","$33.80","2015-08-28","1497","159","$26.26","2015-08-29","926","107","$18.50","2015-08-30","1188","154","$18.21","2015-08-31","1598","182","$31.36","2015-09-01","875","107","$0.00","Date","0","0","$0.00"

and it should be more like

"Date","Impressions","Clicks","Total"
"2015-08-26","1887","207","$28.07"
"2015-08-27","1974","206","$33.80"
"2015-08-28","1497","159","$26.26"
"2015-08-29","926","107","$18.50"
"2015-08-30","1188","154","$18.21"
"2015-08-31","1598","182","$31.36"
"2015-09-01","875","107","$0.00"
"Date","0","0","$0.00"
Kara
  • 6,115
  • 16
  • 50
  • 57

0 Answers0