Exporting Data to Excel file in Rails

There are two ways of doing the same thing first is to use the gem to_xls-rails and another is without gem I am gonna explain both approaches:

Approach 1:  Using gem  'to_xls-rails'

1.) bundle install

2.)Your Controller
def index
  @posts = Post.all
  respond_to do |format|
    format.html # don't forget if you pass html
    format.xls { send_data(@posts.to_xls) }
  end
end
3.)Your View
<%= link_to 'Excel Download', posts_path(:format => :xls) %>
4.)config/initializers/mime_type.rb
Mime::Type.register "application/vnd.ms-excel", :xls
 
Another way or standard way without any gem

Approach 2:  Without any gem

 
1.) config/initializers/mime_type.rb
 Mime::Type.register "application/xls", :xls 
2.)Your Controller
def index  @risks = logged_user.risks
  respond_to do |format|
    format.html
    format.xls  #This line will simply find the xls.erb file in its view 
  end
 end
or
 
   format.xls { send_data(@risks.to_xls)  #this will send the xls file to download without 
   requiring for view xls.erb file
 
 
 

Comments

Popular posts from this blog

SAML IdP initiated SSO Resources Rails

Basic app in Rails 5 api mode

OAuth2 Overview