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!
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.