Reading Google Sheet as CSV file

Today I was in a need of reading a google sheet file, as online csv file, without downloading offline copy of the file, and i found the below solution, and liked to share with the community.

  1. In Googlesheets:
  • Publish the sheet under consideration as csv file, using File -> Publish to the web, make sure to select the option “Automatically republish when changes are made”
  • Copy the link provided by googleSheets for the csv connectivity

  1. In Go lang
  • Use the below code:
// file main.go
package main

import (
	"encoding/csv"
	"fmt"
	"net/http"
)

func readCSVFromURL(url string) ([][]string, error) {
	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	reader := csv.NewReader(resp.Body)
	reader.Comma = ','
	data, err := reader.ReadAll()
	if err != nil {
		return nil, err
	}

	return data, nil
}

func main() {
	url := "https://docs.google.com/spreadsheets/d/e/xxxxxsingle=true&output=csv"
	data, err := readCSVFromURL(url)
	if err != nil {
		panic(err)
	}

	for idx, row := range data {
		// skip header
		if idx == 0 {
			continue
		}

		if idx == 6 {
			break
		}

		fmt.Println(row[2])
	}
}
//


  [1]: https://i.stack.imgur.com/nxEcH.png
2 Likes

Fixed, Thanks for the feedback