Thursday, October 13, 2016

Using Gem 'to_spreadsheet' to Generate XLSX FIle in Rails

Using Gem 'to_spreadsheet' to Generate XLSX FIle in Rails

Now, let’s find out how to generate Excel file in Rails.

After searching many gems, I found that axlsx is a very well-designed for my purpose. However, it generates xlsx file by building up the components piece by piece. I need a quick solution which can generates a xlsx file from html file. Then I found a gem called to_spreadsheet that is totally full-filled my needs!

Actually, to_spreadsheet is a wrapper of axlsx. It simplifies the usage and allows us using the existing view template to generate xlsx file.

Installation

Put it in Gemfile.

gem 'to_spreadsheet'

Likewise, bundle install.

Usage

1.Put the code in the response_tosection of the controller. Like:

def show
  @orderdetails = @order.orderdetails.includes(:model, :size, :color)
    respond_to do |format|
    fn = "order_#{@order.po_number}_#{Time.now.strftime("%Y-%m-%d %H:%M:%S")}"

    format.xlsx { render xlsx: :show, filename: fn }
  end
end

2.Copy the show.html.erb to a new file and rename it as show.xlsx.erb.
3. Remove all the link_to tags in the file to prevent them from showing in the xlsx file.
4. Try to put the data you need to show in <table></table> block.

Done!

No comments:

Post a Comment