Search code examples
rubygoogle-api

How do I add data to a Google Sheet from Ruby?


There's a Ruby Quickstart guide in Google's developers site, but it only demonstrates how to get data from a spreadsheet, not adding data to it.

Is there some easy example out there explaining how to do it?


Solution

  • Let's suppose you have an array of emails you want to add to a spreadsheet:

    def generate_emails
      10.times.map { |i| ["email#{i}@example.com"] }
    end
    

    Now, after initializing the API (just after calling the authorize method), prepare the value range object with the data, and append it to the spreadsheet using the API:

    # Adds the email addresses to the spreadsheet
    value_range_object = Google::Apis::SheetsV4::ValueRange.new(values: generate_emails)
    response = service.append_spreadsheet_value(
               SPREADSHEET_ID,
               RANGE,
               value_range_object,
               value_input_option: VALUE_INPUT_OPTION)
    

    Don't forget to define the SPREADSHEET_ID, and the other two constants:

    RANGE = 'Sheet1!A1'
    VALUE_INPUT_OPTION = 'RAW'
    

    This will add your data to the existing content (it will not be overwritten).