Gem Of The Week: Creek


Being able to parse and import existing data into your Rails app can play a large role in being able to provide the best experience to your users, but more often than not, that data isn’t in a Ruby-friendly format.

Enter Creek.

Creek is a gem that allows you to parse an Excel file by looping through the sheets and rows with enumerators and generating usable Ruby hashes for you to process.

To get started, you need to install the gem (either with the terminal or through the Gemfile), then you need to:

require 'creek'

so that you have access to all of the features of Creek.

Then, identify your Excel file and create a new Book with Creek:

excel_file = "data/excel_files/sample_file.xlsx"

Now that you have access to the Excel file you can start playing around with the content of the file itself:

sheets = excel_file.sheets

this provides a way to interact with the sheets within your Excel file and you can iterate over them with a simple:

sheets.each do |sheet|

this provides a way to view the visible name of the sheet within the Excel file (you can also access information like the state of the sheet with “sheet.state”)

In order to access the rows of each sheet you first need to have an individual sheet available to you:

sheet = sheets[0]

Next, you can iterate over the rows with a simple:

sheet.rows.each do |row|
    puts row

“row” will be returned to you as a hash of content keyed on cell number (like “A1”, “B1”, “C1”, etc.). For example, a sample row might be:

{"A1" => "First Name", "B1" => "Last Name", "C1" => "Phone Number"}

which provides a very easy way to get directly at the content of the Excel file.

Gems allow you to quickly and effortless add new and powerful features to your Ruby / Ruby on Rails app and Creek allows you to seamlessly integrate the ability to quickly and easily parse Excel-based data and have it available to you within your app.