Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export data from model to excel file on rubyonrails

I'm trying to export data from my models to an excel spreadsheet. I have seen 3 ways

  1. Using the spreadsheet gem which I didn't understand how to use it, the examples I saw was writing to a local file but I'm looking to generate a file every time user clicks on a link.
  2. Creating a method called export, and running the query there, then making a export.xls file in my view, and that file creating the table I want to be exported to the excel file, but this approach don't allow me to create multiple sheets.
  3. Followed this tutorial, http://oldwiki.rubyonrails.org/rails/pages/HowToExportToExcel, but here doesn't show how to put the link in the view, looks to me that I'm missing something in the routes, I can give github so you can take a look at my code if needed.
like image 624
Luis D Urraca Avatar asked Jul 19 '11 21:07

Luis D Urraca


People also ask

How do you export data from a data model?

Export the data model to XMLIn Oracle Policy Modeling, select View | Data Model. The data model view will open in the right hand pane. In this view, right-click anywhere and select Export to XML... In the Save As dialog box specify a location to save the data model to.

How do I export dataset to Excel from python?

Algorithm: Create the DataFrame. Determine the name of the Excel file. Call to_excel() function with the file name to export the DataFrame.


2 Answers

My choice is to just manualy generate CSV file. Like:

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

CSV file can be opened with excel or any other spreadsheet soft.

like image 102
fl00r Avatar answered Sep 28 '22 04:09

fl00r


I'm using writeexcel in my most recent Rails project. A fast and simple to use way to export excel files directly - no CSV!

To use it directly in your views you have to register writeexcel as a template handler - this is excalty what my gist does. Then create a new template like export.xls.writeexcel, insert your code and you're good to go.

like image 34
Mario Uher Avatar answered Sep 28 '22 03:09

Mario Uher