简体   繁体   English

我们如何从 google sheet url 读取文件并将其数据转换为 vanillaJS/jsquery 中的 json?

[英]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.我正在做一个项目,我需要从 google sheet url 读取文件,然后将其内容转换为 json。 Then I will use that json object for showing content in the frontend.然后我将使用该 json 对象在前端显示内容。 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?但我只想知道我们如何从 google sheet url 读取 excel 文件,然后是否有任何内置函数或外部库可以转换 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)要通过应用脚本读取电子表格并获取 json,请尝试(您需要知道电子表格的 id 和工作表的 gid)

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")要通过 html 阅读,请尝试使用此脚本(定义 id 为“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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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