[Awesome Ruby Gem] Use creek gem to parse large Excel (xlsx and xlsm) files with images
creek
Creek is a Ruby gem that provides a fast, simple and efficient method of parsing large Excel (xlsx and xlsm) files.
Features
-
parse images with
with_images
andimages_at
. -
map cell names with letter and number(A1, B3 and etc) by default.
Installation
You can install it as a gem:
1 | gem install creek |
or add it into a Gemfile (Bundler):
1 | # Gemfile |
Usages
Basic Usage
Creek can simply parse an Excel file by looping through the rows enumerator:
1 | require 'creek' |
Filename considerations
By default, Creek will ensure that the file extension is either *.xlsx or *.xlsm, but this check can be circumvented as needed:
1 | path = 'sample-as-zip.zip' |
By default, the Rails file_field_tag uploads to a temporary location and stores the original filename with the StringIO object. (See this section of the Rails Guides for more information.)
Creek can parse this directly without the need for file upload gems such as Carrierwave or Paperclip by passing the original filename as an option:
1 | # Import endpoint in Rails controller |
Parsing images
Creek does not parse images by default. If you want to parse the images, use with_images method before iterating over rows to preload images information. If you don’t call this method, Creek will not return images anywhere.
Cells with images will be an array of Pathname objects. If an image is spread across multiple cells, same Pathname object will be returned for each cell.
1 | sheet.with_images.rows.each do |row| |
Images for a specific cell can be obtained with images_at method:
1 | puts sheet.images_at('A1') # => [#<Pathname:/var/folders/ck/l64nmm3d4k75pvxr03ndk1tm0000gn/T/creek__drawing20161101-53599-274q0vimage1.jpeg>] |
Creek will most likely return nil for a cell with images if there is no other text cell in that row - you can use images_at method for retrieving images in that cell.
Remote files
1 | remote_url = 'http://dev-builds.libreoffice.org/tmp/test.xlsx' |
Mapping cells with header names
By default, Creek will map cell names with letter and number(A1, B3 and etc). To be able to get cell values by header column name use with_headers (can be used only with #simple_rows method!!!) during creation (Note: header column is first string of sheet)
1 | creek = Creek::Book.new file.path, with_headers: true |
References
[2] creek | RubyGems.org | your community gem host - https://rubygems.org/gems/creek