Frequently developers need to write data to files like .csv and .xlsx. This article will discuss this common use case in Ruby on Rails applications.
We will be using
spreadsheet gem and writing a rake task to export data to the file.
First, set up an application.
1 2 3 rails new spreadsheet_app rails generate model Post title body author rails db:create db:migrate
Now seed in some data.
1 2 3 4 # db/seeds.rb Post.create(title: "Working with Spreadsheet", body: "This post will discuss how to write to spreadsheets.", author: "Mike") Post.create(title: "Working with Devise", body: "This post will discuss how to authenticate with Devise.", author: "John")
spreadsheet gem and run
1 gem spreadsheet
As mentioned earlier, we will be exporting the data to the Excel sheet through a rake task, which we will generate now.
1 rails g task posts export
lib/tasks/posts.rake, put the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 namespace :posts do desc "This task will export posts to excel sheet" task export: :environment do book = Spreadsheet::Workbook.new sheet = book.create_worksheet :name => 'Posts' posts = Post.all posts.each_with_index do |post, i| sheet.row(i).push post.title, post.body, post.author end book.write 'Posts.xls' end end
Now test the implementation. In your terminal, run the following command:
1 rake posts:export
It should now create a file named Posts.xls and export the data successfully. Happy exporting!