Skip to content

AndreyAzimov/ruby-on-rails-google-sheet-csv

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

46 Commits
 
 
 
 
 
 

Repository files navigation

How to get data from Google Sheet using Ruby on Rails?

alt text

This method will help you to download data from Google Sheet as CSV to Rails public folder (or any other folder) and parse it as array of hashes.

This is pure Ruby implementation. No gems. Just a single file.

Data in the Google Sheet is updating live automatically.

It's working on Heroku.

Usage

  1. Copy the following code and save it as google_sheet.rb to /app/models/ (if you are using Rails)
class GoogleSheet
  require 'open-uri'
  require 'csv'

  def self.get url

    csv_file = "#{Rails.root}/public/data.csv"
    
    # save csv file from url
    open(url) {|f| File.open(csv_file,"wb") {|file| file.write f.read}}

    data = []
  
    # parse each csv row
    CSV.open(csv_file, headers: true).each{|row| data << row.to_hash}

    return data
  end
end
  1. Usage:
url = "https://docs.google.com/spreadsheets/d/e/2PACX-1vSf0VkQ9iCihfZqlNDg04GTso_seU8Pom53YtPjGc6PrUlJ1bY9b6WHARo2MQFJnLbrt4P7-PlnNm4_/pub?gid=0&single=true&output=csv"
data = GoogleSheet.get url

Prepare your Google Sheet

  1. Open your Google Sheet e.g. this one
  2. File -> Share -> Publish to the web
  3. Entire Document -> Sheet1
  4. Web page -> Comma-separated values (.csv)
  5. Share
  6. Copy the url that should look like this: https://docs.google.com/spreadsheets/d/e/2PACX-1vSf0VkQ9iCihfZqlNDg04GTso_seU8Pom53YtPjGc6PrUlJ1bY9b6WHARo2MQFJnLbrt4P7-PlnNm4_/pub?gid=0&single=true&output=csv

Options:

  • If you are not using Ruby on Rails change csv file path to your: csv_file = "#{Rails.root}/public/data.csv"
  • if your CSV doesn't have headers change headers: false
  • If you want to have JSON output use render json: data in your controller (Ruby on Rails only).

About

Ruby on Rails Google Sheet CSV

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages