Ruby on Rails Export Excel without gem and Change the filename excel

07.51 Muhamad Akbar Bin Widayat 5 Comments

Ruby on Rails logo
Ruby on Rails logo (Photo credit: Wikipedia)
Hi Everyone,

Currently I want to share to you how to make export function without gem and I change/modify the filename. Please follow me below:
1. Add mime type on config/initializers/mime_types.rb
    Mime::Type.register "application/xls", :xls
2. Add on your controller
    def index
      @tabulars = Tabular.all
      filename = "data_users.xls"
      respond_to do |format|
        format.html
        format.xls { headers["Content-Disposition"] = "attachment; filename=\"#{filename}\"" }
      end
    end
3. Add on your view:
    <%= link_to "Export",  tabulars_path(format: "xls") %>

4, Add format index.xls.erb file:
       <table>
          <tr>
             <th>Name</th>
          </tr>
          <% @tabulars.each do |tabular| %>
             <tr><td><%= tabular.name %></td></tr>
          <% end %>
       </table>

I hope this article can help you. :)
Enhanced by Zemanta

5 komentar:

  1. Anonim10.13

    nice thanks :)

    BalasHapus
  2. Anonim16.46

    Any idea how to export multiple sheets?

    BalasHapus
    Balasan
    1. I have 2 options to you.
      1. You can convert to zip first.
      2. You can create a sheet need a page with extension xls.erb

      Hapus
  3. Magnifique! Merci beaucoup (y)

    BalasHapus

terimakasih komentarnya