首页 > 解决方案 > 如何通过谷歌脚本(gs)将整个谷歌电子表格作为文本文件读取(按行)

问题描述

我有一个带有 json 格式文本的谷歌表,它位于随机单元格中,需要通过谷歌应用程序脚本阅读。有一些方法可以按列或作为实际上插入不必要的分号的数组来读取它。请告知如何类似于 UrlFetchApp.fetch 和 JSON.parse 但直接从电子表格中逐行读取,跳过空单元格?例如 A1 B1 C1 ... A2 B2 C2 ... 等(无空格)

标签: jsongoogle-sheetsscript

解决方案


function readJson(){
  const sh = SpreadsheetApp.getActive().getSheetByName("Sheet1")
  const allValues = sh.getDataRange().getValues()
  const arrJson = []
  allValues.forEach(row=>{
    row.filter(cell=>cell).forEach(cell=>{
      try{
        const json = JSON.parse(cell)
        arrJson.push(json)
      } catch(ignore){
        // JSON parse failed, probably not JSON
      }
    })
  })

  // arrJson contains all json data from cells in Sheet1
}

推荐阅读