Nel

Nel

  • NA
  • 716
  • 1.1m

Problem with exporting data from client side in excel

Jan 12 2015 3:33 PM

Hi,

I use google maps server for retrieving travel time data, and I want to export these data in excel

I have this code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TravelTimeCalculation.aspx.cs" Inherits="TravelTime.TravelTimeCalculation" %>

<!DOCTYPE html>
<html>
  <head>
    <title>Distance Matrix service</title>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <style>
         html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

      #map-canvas {
        height: 50%;
        width: 100%;
      }
      #content-pane {
        float:initial;
        width:100%;
        /*padding-left: 2%;*/
      }
      #outputDiv {
        font-size: 11px;   
      }
      /*html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

      #map-canvas {
        height: 100%;
        width: 50%;
      }
      #content-pane {
        float:right;
        width:48%;
        padding-left: 2%;
      }
      #outputDiv {
        font-size: 11px;
      }*/
    </style>
          
 <%-- <a href="#" id="downloadLink">Download the csv file</a> <%-- 09.10--%>
     <%-- <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>--%>

<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
    <script>

        var map;
        var geocoder;
        var bounds = new google.maps.LatLngBounds();
        var markersArray = [];

        var origin1 = new google.maps.LatLng(26.368628, -80.137214);
        var origin2 = new google.maps.LatLng(26.368311, -80.131249);
        var origin3 = new google.maps.LatLng(26.368215, -80.128964);
        var origin4 = new google.maps.LatLng(26.368099, -80.125042);
        var origin5 = new google.maps.LatLng(26.368176, -80.120965);
        var origin6 = new google.maps.LatLng(26.367907, -80.116363);
        var origin7 = new google.maps.LatLng(26.367475, -80.114678);
        var origin8 = new google.maps.LatLng(26.365442, -80.106143);
        var destinationA = new google.maps.LatLng(26.368311, -80.131249);
        var destinationB = new google.maps.LatLng(26.368215, -80.128964);
        var destinationC = new google.maps.LatLng(26.368099, -80.125042);
        var destinationD = new google.maps.LatLng(26.368176, -80.120965);
        var destinationE = new google.maps.LatLng(26.367907, -80.116363);
        var destinationF = new google.maps.LatLng(26.367475, -80.114678);
        var destinationG = new google.maps.LatLng(26.365442, -80.106143);
        var destinationH = new google.maps.LatLng(26.362884, -80.098408);

        var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
        var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';

        function initialize() {
            var opts = {
                center: new google.maps.LatLng(26.368049, -80.116693),
                zoom: 15
            };
            map = new google.maps.Map(document.getElementById('map-canvas'), opts);
            geocoder = new google.maps.Geocoder();
        }

        origin = origin1 + "," + origin2 + "," + origin3;
        destin = destinationA + "," + destinationB + "," + destinationC;

        //var el = origin.split(";");
        //var elo = [el[0] + ", "];
        //for (var j = 1; j < el.length ; j++) {
        //    elo += [el[j] + ", "];
        //}

        var csvContent = "data:text/csv;charset=utf-8,";

        //alert(el.length+ el[0] + "" + el[1] + "" + el[2]);
        //   alert(origin);

        //var eld = destin.split(";");
        //var elde = [eld[0] + ", "];
        //for (var j = 1; j < eld.length ; j++) {
        //    elde += [eld[j] + ", "];
        //}

        //  alert(eld[0] + "" + eld[1] + "" + eld[2]);
        //   alert(destin);

        function calculateDistances() {
            // for (var i = 0; i <= el.length; i++) {
            var service = new google.maps.DistanceMatrixService();
            service.getDistanceMatrix(
              {
                  origins: [origin1, origin2, origin3, origin4, origin5, origin6, origin7, origin8], //[origin]
                  destinations: [destinationA, destinationB, destinationC, destinationD, destinationE, destinationF, destinationG, destinationH], //[destin]
                  travelMode: google.maps.TravelMode.DRIVING,
                  unitSystem: google.maps.UnitSystem.METRIC,
                  avoidHighways: false,
                  avoidTolls: false
              }, callback);
            // }
        }
        //var rows = [];

        //  var data = [];
        //  var csvRows = [];
        var csvData = [['Section number', 'Distance', 'Duration']];
        // var csvData = [['origins','destinations','distance', 'duration']]; //new Array();
        //var fileName = 'TravelTime.csv';
        var csvString = "";
        //  var t = 0;

        function callback(response, status) {
            if (status != google.maps.DistanceMatrixStatus.OK) {
                alert('Error was: ' + status);
            } else {
                var origins = response.originAddresses;
                var destinations = response.destinationAddresses;
                var outputDiv = document.getElementById('outputDiv');
                outputDiv.innerHTML = '';
                deleteOverlays();

                for (var i = 0; i < origins.length; i++) {
                    var results = response.rows[i].elements;
                    addMarker(origins[i], false);
                    // for (var j = 0; j < results.length; j++) {
                    addMarker(destinations[i], true); //was j
                    outputDiv.innerHTML += origins[i] + ' to ' + destinations[i] //was destination[j]
                        + ': ' + results[i].distance.text + ' in '  //results[j].distance.text
                        + results[i].duration.text + '<br>'; //results[j].distance.text
                    //csvData.push([origins[i], destinations[i], results[i].distance.text, results[i].duration.text])
                    csvData.push([i, results[i].distance.text, results[i].duration.text])
                    //downloadInnerHtml(filename, 'outputDiv', csv);

                    // csvRows.push(data[i].join(','));
                    // var csvString = csvRows.join("%0A");
                    ////         data.forEach(function (infoArray, index) {

                    ////dataString = infoArray.join(",");
                    ////csvContent += index < infoArray.length ? dataString + "\n" : dataString;
                    //var csvString = csvRows.join("\n");
                    //console.log(csvString);
                    //var csvWin = window.open("","","");
                    //csvWin.document.write('<meta name="content-type" content="text/csv">');
                    //csvWin.document.write('<meta name="content-disposition" content="attachment;  filename=data.csv">  ');
                    //csvWin.document.write(csvString);
                    // });    
                }
                var csvRows = []
                for (var n = 0, l = csvData.length; n < l; ++n) {
                    csvRows.push(csvData[n].join(' to '));   // unquoted CSV row
                    //csvRows.push(csvData[n].join(' in '));
                    //csvRows.push(csvData[n].join(' : '));
                }
                csvString = csvRows.join('\n');
                //var data = outputDiv.innerHTML;
                //csvData.push = ('"origins", "destinations", "results.distance.text", "results.duration.text"');

                //data.forEach(function (item, index, array) {
                //    csvData.push('"' + item.origins + '","' + item.destinations + '","' + item.results.distance.text + '","' + results.duration.text + '"');
                //});


            }
            exportCSV();
            //  t++;
            //var encodedUri = encodeURI(csvContent);
            //window.open(encodedUri);

            //var encodedUri = encodeURI(csvContent);
            //var link = document.createElement("a");
            //link.setAttribute("href", encodedUri);
            //link.setAttribute("download", "my_data.csv");

            //link.click();

        }

        //function downloadInnerHtml(filename, elId, mimeType) {
        //    var elHtml = document.getElementById(elId).innerHTML;
        //    var link = document.createElement('a');
        //    mimeType = mimeType || 'text/csv';

        //    link.setAttribute('download', filename);
        //    link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
        //    link.click();
        //}


        function addMarker(location, isDestination) {
            var icon;
            if (isDestination) {
                icon = destinationIcon;
            } else {
                icon = originIcon;
            }
            geocoder.geocode({ 'address': location }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    bounds.extend(results[0].geometry.location);
                    map.fitBounds(bounds);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location,
                        icon: icon//,
                        //title: results[0].geometry.location
                    });
                    markersArray.push(marker);
                } else {
                    alert('Geocode was not successful for the following reason: '
                      + status);
                }
            });

        }

        function deleteOverlays() {
            for (var i = 0; i < markersArray.length; i++) {
                markersArray[i].setMap(null);
            }
            markersArray = [];
        }

        //var a = document.createElement('a');
        //a.href = 'data:attachment/csv,' + csvString;
        //a.target = '_blank';
        //a.download = 'myFile.csv,' + encodeURIComponent(csvString);;
        //a.innerHTML = "Click me to download the file.";
        //document.body.appendChild(a);

        //google.maps.event.addDomListener(downloadLink,'click',(function () {
        //    downloadInnerHtml(fileName, 'main', 'text/csv');
        //}));

        google.maps.event.addDomListener(window, 'load', initialize);
        setInterval(function () { initialize(); calculateDistances(); }, 20000); //downloadInnerHtml(filename, 'outputDiv', csv);

        function exportCSV() {
            //download stuff
            var buffer = csvData.join("\n");
            var uri = "data:text/csv;charset=utf8," + encodeURIComponent(buffer);
            var fileName = "data.csv";

            var link = document.createElement("a");
            if (link.download !== undefined) { // feature detection
                // Browsers that support HTML5 download attribute
                link.setAttribute("href", uri);
                link.setAttribute("download", fileName);
            }
            else if (navigator.msSaveBlob) { // IE 10+
                link.addEventListener("click", function (event) {
                    var blob = new Blob([buffer], {
                        "type": "text/csv;charset=utf-8;"
                    });
                    navigator.msSaveBlob(blob, fileName);
                }, false);
            }
            else {
                // it needs to implement server side export
                link.setAttribute("href", "http://www.example.com/export");
            }
            link.innerHTML = "Export to CSV";

            document.body.appendChild(link);

        }
        //var a = document.createElement('a');
        //a.href = 'data:attachment/csv,' + csvString;
        //a.target = '_blank';
        //a.download = 'myFile.csv';

        //document.body.appendChild(a);
        //a.click();


        ////var encodedUri = encodeURI(csvContent);
        ////window.open(encodedUri);


        ////var encodedUri = encodeURI(csvContent);
        ////var link = document.createElement("a");
        ////link.setAttribute("href", encodedUri);
        ////link.setAttribute("download", "my_data.csv");

        ////link.click();
    </script>
  </head>
  <body>
    <div id="content-pane">
       
        <table align="center" style="background-color:antiquewhite; width:100%" >
    
             <div id="inputs">         
            <tr>
         <td>
       <pre>
        origin1 = "St Andrews Blvd;     destinationA = "Town Center Rd";
        origin2 = "Town Center Rd";     destinationB = "Butts Rd";
        origin3 = "Butts Rd";           destinationC = "Renaissance Rd";
        origin4 = "Renaissance Rd";     destinationD = "ISB";
        origin5 = "ISB";                destinationE = "INB";
        origin6 = "INB";                destinationF = "Airport Rd";
        origin7 = "Airport Rd";         destinationG = "NW 10th Ave";
        origin8 = "NW 10th Ave";        destinationH = "NW 13th Ave";                      
       </pre>
              </td>
           </tr>       
            <tr>
                 <td>Calculated Distance and Travel Time</td>
            </tr>               
           <tr>
               <td>
                    <pre>
                    <div id="outputDiv"></div>
                    </pre>
                   </td>
                </tr>     
       </table>

       <%-- <table>
             <tr>
                <pre>
                <div id="map-canvas"></div>
                    </pre>
            </tr>
        </table>--%>
 <%--     <p><button type="button" onclick="exportCSV();">Export to CSV</button></p>--%>
     <%--  <div id="outputDiv"></div>--%>
      </div>

      <div id="main">
          <%--<span>outputDiv.innerHTML</span>--%>
      </div>

    <%--</div>--%>
    <div id="map-canvas"></div>
  </body>
</html>

So I get an excel file to download the data, but since the data on the client side are automatically updated, the excel file is downloaded every time the data is updated

I would like the data to be updated in the same excel file, not to get lot of updated excel files whenever the data received from google map are updated

Can anybody help me please how to update the same excel file with the new received data?

Thank you



Answers (2)