繁体   English   中英

Ruby on Rails导出Excel数据文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM