Autonomía digital y tecnológica

Código e ideas para una internet distribuida

Linkoteca. CSV


Every document in Google Sheets supports the «Chart Tools datasource protocol», which is explained (in a rather haphazard way) in these articles:

«Creating a Chart from a Separate Spreadsheet»
«Query Language Reference»
«Implementing the Chart Tools Datasource Protocol»

To download a specific sheet as a CSV file, replace {key} with the document’s ID and {sheet_name} with the name of the sheet to export:

https://docs.google.com/spreadsheets/d/{key}/gviz/tq?tqx=out:csv&sheet={sheet_name}

The datasource protocol is quite flexible. Various other options include:

Response Format: Options include tqx=out:csv (CSV format), tqx=out:html (HTML table), and tqx=out:json (JSON data).

Export part of a sheet: Supply the range={range} option, where the range can be any valid range specifier, e.g. A1:C99 or B2:F.

Execute a SQL query: Supply the tq={query} option, such as tq=SELECT a, b, (d+e)*2 WHERE c < 100 AND x = 'yes'. Export textual data: Supply the headers=0 option in case your fields contain textual data, otherwise they might be cut out during export.

First I take the whole CSV file and split it into an array of lines. Then, I take the first line, which should be the headers, and split that by a comma into an array. Then, I loop through all the lines (skipping the first one) and inside, I loop through the headers and assign the values from each line to the proper object parameters. At this point, you probably want to just return the JavaScript object, but you can also JSON.stringify the result and return the JSON object.