CSV Export from view

Hi,

Whcih is the best way to export a table as csv ? I already have the
table I want to export as a 2d array, and has disabled the layout for
that view. But I am bit confused about the final output, my current
pathetic attempt at CSV writing is

<% for row in @report
for cell in row
puts (cell)
end
end %>

but their ought to be a better way.

Any hits with clue stick is much appreciated!

raj

I would do it in a class method, then render :text.
Also, you could do
@headers[“Content-Type”] = “text/plain”
to cause the browser to want to download instead of display the data.

but their ought to be a better way.

Any hits with clue stick is much appreciated!

CSV… http://stdlib.rubyonrails.org/libdoc/csv/rdoc/index.html

Look at the CSV:Writer class…

Just did this today.

Get the FasterCSV gem. Once you’ve got it, require it in environment.rb.
Here’s an abbreviated version of my working controller method.
Copy/paste/modify. And you’re done!

def export_to_csv
@users = User.find(:all)

csv_string = FasterCSV.generate do |csv|
# header row
csv << [“id”, “first_name”, “last_name”]

# data rows
@users.each do |user|
  csv << [user.id, user.first_name, user.last_name]
end

end

send it to the browsah

send_data csv_string,
:type => ‘text/csv; charset=iso-8859-1; header=present’,
:disposition => “attachment;
filename=users_#{Time.now.strftime
(”%m-%d-%Y")}.csv"
end


Scott B.
Electro Interactive, Inc.
Office: 813-333-5508

Thanks a lot! I am now able to generate CSV successfully!

raj