Google Sheets API client
README.md

gsheets #

Google Sheets API client and command-line tool.

To get a Google spreadsheet into a script, a report or a diff, people usually export it by hand as CSV, and the export drops the formulas and the comments. gsheets reads spreadsheets through the Google Sheets v4 REST API instead. It fetches metadata and cell values, returns formulas either evaluated or as source, as the caller asks, and prints a range as CSV or as a Markdown table whose footnotes hold the cell comments. It never writes to a spreadsheet. Authentication goes through gauth, and reading needs the spreadsheets.readonly OAuth scope.

Installation #

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam install gsheets

Usage #

Most programs need four functions: Gsheets.get, Gsheets.values, Gsheets.Csv.of_values and Gsheets.Markdown.of_values. This one fetches a range as CSV:

let fetch_csv http ~token ~spreadsheet_id ~range =
  match Gsheets.values http ~token ~spreadsheet_id ~range () with
  | Error (`Msg m) -> Error m
  | Ok v -> Ok (Gsheets.Csv.of_values v)

With gauth and Eio around it, a complete program looks like this:

let run env ~key_path ~spreadsheet_id ~range =
  Eio.Switch.run @@ fun sw ->
  let http = Requests_eio.v ~sw ~mono:env#mono_clock ~clock:env#clock env#net in
  let clock = Eio.Stdenv.clock env in
  match Gauth.Service_account.of_file key_path with
  | Error (`Msg m) -> failwith m
  | Ok key ->
      match
        Gauth.Service_account.token http ~clock
          ~scopes:[ Gsheets.scope_readonly ] key
      with
      | Error (`Msg m) -> failwith m
      | Ok token ->
          match Gsheets.values http ~token ~spreadsheet_id ~range () with
          | Ok v -> Fmt.pr "%s" (Gsheets.Csv.of_values v)
          | Error (`Msg m) -> Fmt.pr "fetch failed: %s@." m

Formulas vs values #

The Sheets API renders each cell according to a valueRenderOption, which ~render selects:

let formulas http ~token ~spreadsheet_id ~range =
  Gsheets.values http ~token ~render:Gsheets.Formula
    ~spreadsheet_id ~range ()
  • Formatted_value, the default, gives the strings the UI shows, such as "$1,234.50" or "50%".
  • Unformatted_value gives numbers and booleans as JSON numbers and booleans and dates as serial numbers. A formula comes back as its result.
  • Formula gives a formula cell as its source text, such as "=SUM(B2:B10)", and any other cell as Unformatted_value would.

Gsheets.Values.Cell.is_formula_source is true iff the cell is a string that starts with =. It looks only at the text, so it means something only for values fetched with ~render:Gsheets.Formula. With the other options the formulas have already been evaluated and their source is gone.

Spreadsheet metadata #

Gsheets.get fetches the structure of a spreadsheet (its title, its sheets and their grid sizes) without the cell data:

let titles http ~token ~spreadsheet_id =
  match Gsheets.get http ~token spreadsheet_id with
  | Error (`Msg m) -> Error m
  | Ok ss ->
      Ok (List.map Gsheets.Sheet.title (Gsheets.Spreadsheet.sheets ss))

Markdown rendering #

Gsheets.Markdown.of_values turns a block of values into a GFM pipe table whose header is the first row:

let to_markdown http ~token ~spreadsheet_id ~range =
  match Gsheets.values http ~token ~spreadsheet_id ~range () with
  | Error (`Msg m) -> Error m
  | Ok v -> Ok (Gsheets.Markdown.of_values v)

Comments #

Comments on a sheet are stored on the Drive file behind it, so fetching them needs the drive.readonly scope as well as the Sheets one. Given the optional ~comments argument, Gsheets.Markdown.of_values adds each comment as a GFM footnote on the cell its anchor points to:

let to_md_with_comments http ~token ~spreadsheet_id ~range =
  match Gsheets.values http ~token ~spreadsheet_id ~range () with
  | Error (`Msg m) -> Error m
  | Ok v ->
      match Gsheets.Comments.list http ~token spreadsheet_id with
      | Error (`Msg m) -> Error m
      | Ok cs -> Ok (Gsheets.Markdown.of_values ~comments:cs v)

A comment whose anchor is outside the rendered range, or cannot be parsed, goes into a ## Comments blockquote section at the end. CSV has no way to annotate a cell, so Gsheets.Csv.of_values drops comments, and the CLI warns when --comments is used with --format=csv.

Scopes #

let readonly = Gsheets.scope_readonly
let readwrite = Gsheets.scope_readwrite

An HTTP error comes back with the response status in its Msg payload: 401 for a token that is invalid or has expired, 403 for a missing scope or no access, and 404 for an unknown spreadsheet id.

CLI #

The package also installs a gsheets binary. It works like gdocs and shares that tool's login, stored in $XDG_CONFIG_HOME/google/:

$ gsheets install     # one-time OAuth client setup
$ gsheets login       # authorize your Google account
$ gsheets get  <spreadsheet-id>
$ gsheets values <spreadsheet-id> <range> [--render formula] [--format csv|md|json] [--comments]

License #

ISC. See LICENSE.md.