Ruby on Rails 3

I have a table that is not shown on my application. I want to export the table to excel from the console.

Is there way to export a database table to an excel file from the console?

Thank you

Here is what I have so far:

require 'csv'

file = "#{Rails.root}/public/survey.csv"

userrefs = Survey.all

CSV.open( file, 'w' ) do |writer|
 userrefs.each do |ur|
   writer << ur.attributes.values_at(*column_names)
 end
end

When I enter require 'csv' it returns false. How do you make it true? Also, the *column_names is undefined.

有帮助吗?

解决方案

As mentioned in the comments an easy approach is using format.xls function to render an excel file from the console. Ryan Bates video covers Excel outputs extensively.

其他提示

You can connect to the database table using the existing driver or, if you prefer a more high-level API, you can create an ActiveRecord model or use the Sequel gem.

Once connected, simply use the Ruby CSV library (it's in the standard library, so no additional library is required) to dump the content into a CSV file.

CSV files can be easily read from Excel.

PS. Just to use the appropriate words, that is not a Rails table. It's a database table.

Another interesting approach could be using the activeadmin gem, it's easy to install and allow you to export your tables to csv.

http://www.activeadmin.info/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top