简体   繁体   中英

How can we read file from google sheets url and convert its data into json in vanillaJS/jsquery?

I am working on a project where I need to read a file from google sheets url and then convert its content in json. Then I will use that json object for showing content in the frontend. But I just want to know how can we read an excel file from google sheets url and then are there any built in functions or external library which converts the data in json?

Thanks in advance.

To read a spreadsheet via app script and get the json, try (you need to know the id of the spreadsheet and the gid of the sheet)

const readSheet2json = () => {
  var id = '#######';
  var gid = '######';
  var url = `https://docs.google.com/spreadsheets/d/${id}/gviz/tq?tqx=out:json&tq&gid=${gid}`;
  var txt = UrlFetchApp.fetch(url).getContentText();
  var jsonString = txt.slice(47, -2)
  console.log(jsonString)
}

to read via html, try this script (define an element which id is "json")

var id = '#######';
var gid = '######';
var url = 'https://docs.google.com/spreadsheets/d/'+id+'/gviz/tq?tqx=out:json&tq&gid='+gid;
fetch(url)
  .then(response => response.text())
  .then(data => document.getElementById("json").innerHTML=myItems(data.slice(47, -2))  
  );
function myItems(jsonString){
  var json = JSON.parse(jsonString);
  var table = '<table><tr>'
  json.table.cols.forEach(colonne => table += '<th>' + colonne.label + '</th>')
  table += '</tr>'
  json.table.rows.forEach(ligne => {
    table += '<tr>'
    ligne.c.forEach(cellule => {
        try{var valeur = cellule.f ? cellule.f : cellule.v}
        catch(e){var valeur = ''}
        table += '<td>' + valeur + '</td>'
      }
    )
    table += '</tr>'
    }
  )
  table += '</table>'
  return table
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM