Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you Import data from a Google Sheets?

How to take the first cell of a Google spreadsheet and output it as a string with JavaScript to an HTML document?

I have an HTML document labeled: "Website.html"

<!DOCTYPE html>
<html>
     <head>
        <script>
          var textDisplay = Some code to import spreadsheet cell text;
          document.getElementById("display").innerHTML = textDisplay;
        </script>
     </head>
    <body>
        <p id="display"></p>
    </body>
</html>

and another file in the same folder labeled: "Spreadsheet.xcel" (or whatever file type that is). The first cell contains the text: "Hello".

How do I make the text in the spreadsheet import into the JavaScript of the HTML document?

like image 997
CTOverton Avatar asked May 10 '13 15:05

CTOverton


1 Answers

Your solution will depend on your data source; you included google-spreadsheet, so here's an answer about that. Just stating the obvious to start: A google spreadsheet would not be a file on your server, instead it would be in "the cloud" in a Google Drive.

You can retrieve contents of google spreadsheets from your javascript, and there are examples here in SO:

  • Getting value of a cell from google docs spreadsheet into javascript
  • Access Google-apps public spreadsheet via Javascript

Basic idea for retrieving one cell of data as a string:

  • In Google Drive, create your spreadsheet.
  • Publish the spreadsheet, picking the range A1 for the first cell. You should be provided a URL like:

    https://docs.google.com/spreadsheet/pub?key=SPREADSHEET_KEY&single=true&gid=0&range=A1&output=csv

Example

function loadData() {
  var url="https://docs.google.com/spreadsheet/pub?key=p_aHW5nOrj0VO2ZHTRRtqTQ&single=true&gid=0&range=A1&output=csv";
  xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState == 4 && xmlhttp.status==200){
      document.getElementById("display").innerHTML = xmlhttp.responseText;
    }
  };
  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);
}
<html>
  <body>
    <button type="button" onclick="loadData()">Load Spreadsheet Data</button>
    <div id="display"></div>
  </body>
</html>

You can also see this as a jsfiddle here.

Thanks to GPSVisualizer, who were kind enough to publish a public google spreadsheet I could use for this example.

like image 148
Mogsdad Avatar answered Sep 30 '22 01:09

Mogsdad