[英]ruby on rails export an excel data file
我正在嘗試設計一個網站,允許訪問該網站的任何人下載excel文件。 excel文件僅存儲我想公開獲得的數據。 我正在使用ruby on rails,想知道是否有一種簡單的方法來存儲我的excel電子表格(也許在Assets文件夾中?)並在我的網頁上建立一個鏈接,單擊該鏈接即可下載電子表格。 謝謝!
您可以使用CSV導出(與Excel很好地兼容),因為Ruby在該軟件中具有實現良好的CSV功能。
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
另外,您必須在config / application.rb中require
它:
require 'csv'
require 'rails/all' # Or something resembling to this.
在模型中,將其添加到其中:
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
來源: GoRails(視頻) , RailsCasts
我通過查看相關文章找到了答案 : 如何在Ruby on Rails中提供xls文件鏈接? 然后看着hernanvicente的答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.