1

I am trying to design a website that allows anyone visiting the site to download an excel file. The excel file just stores data that I would like to make publicly available. I am using ruby on rails, and was wondering if there is an easy way to store my excel spreadsheet (maybe in the assets folder?) and make a link on my webpage that when clicked downloads the spreadsheet. Thanks!

2 Answers 2

2

You can use CSV export (works with Excel pretty well) since Ruby has a well implemented CSV feature into the software.

class UsersController < ApplicationController def index @users = User.all respond_to do |format| format.html format.csv { send_data @users.to_csv, filename: "users-#{Date.today}.csv" } end end end 

Also, you have to require it in your config/application.rb:

require 'csv' require 'rails/all' # Or something resembling to this. 

In your model, add this into it:

class User < ActiveRecord::Base def self.to_csv attributes = %w{id email name} CSV.generate(headers: true) do |csv| csv << attributes all.each do |user| csv << attributes.map{ |attr| user.send(attr) } end end end def name "#{first_name} #{last_name}" end end 

Source: GoRails (Video), RailsCasts

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the response. I'm still a little confused (sorry I'm new to coding), where would I upload my csv that I want to export? It is not made from an active record, but rather is a file that I have and want to make available.
Rails relies on ActiveRecord (database) with a model of some method to pass in. For example, if you want to contain records that has username, location, etc, that will need to be stored in the database. Updated with more sources
so there isn't a way to put a excel file somewhere in the rails project and create a link to it in html?
No, at the moment, the assets folder will be only used for stylesheets, javascripts and images (when applicable). I researched through the official documentation from Rails, it only supports that I mentioned above.
0

I figured it out by looking at a related post: How to give the xls file link in Ruby on Rails? and looking at the answer by hernanvicente

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.