How to export data from a model to an excel file on rubyonrails

I am trying to export data from my models to an Excel spreadsheet. I saw 3 ways

  • Using a gem of a spreadsheet that I did not understand how to use, the examples I saw write to a local file, but I am looking to generate a file every time a user clicks on a link.
  • Creating a method called export and running the query there, then making the export.xls file in my view, and this file creates a table I want to export to an excel file, but this approach does not let me create multiple sheets.
  • Following this guide, http://oldwiki.rubyonrails.org/rails/pages/HowToExportToExcel , but it doesn’t show how to put the link in the view, it seems to me that I'm missing something in the routes, I can give github so that you could take a look at my code if necessary.
+6
source share
3 answers

My choice is to simply manually create the CSV file. How:

File.new("data.csv", "w+") do |f| @my_data.each do |data| f << [data.title, data.body, ...].join(", ") + "\n" end end 

A CSV file can be opened using excel or any other soft table.

+7
source

I am using writeexcel in my latest Rails project. Fast and easy way to export excel files directly - no CSV !

To use it directly in your views, you need to register writeexcel as a template handler - this is the exception that my gist . Then create a new template, for example export.xls.writeexcel , paste in your code, and you will go well.

+1
source

You can connect my own gem here, but you can take a look at https://github.com/randym/acts_as_xlsx

This gives you a little more than writeexcel or a spreadsheet in terms of localization, graphs, tables, and formatting from the axlsx gem.

It is also integrated with active coverage ranges and method objectives.

Blogpost with detailed usage examples: http://axlsx.blogspot.com/

http://axlsx.blogspot.jp/2011/12/using-actsasxlsx-to-generate-excel-data.html

http://axlsx.blogspot.jp/2011/12/axlsx-making-excel-reports-with-ruby-on.html

On Github: https://github.com/randym/axlsx

On Rubygems: https://rubygems.org/gems/axlsx

On Rubytookbox: https://www.ruby-toolbox.com/projects/axlsx

This is mainly due to setting up a responder in your controller.

  format.xlsx { xlsx_package = Post.to_xlsx begin temp = Tempfile.new("posts.xlsx") xlsx_package.serialize temp.path send_file temp.path, :filename => "posts.xlsx", :type => "application/xlsx" ensure temp.close temp.unlink end } 

and the next on your model

  class Post < ActiveRecord::Base acts_as_xlsx 

The two blog posts above give a pretty clear walk.

+1
source

Source: https://habr.com/ru/post/893109/


All Articles