简体   繁体   English

Ruby on Rails导出Excel数据文件

[英]ruby on rails export an excel data file

I am trying to design a website that allows anyone visiting the site to download an excel file. 我正在尝试设计一个网站,允许访问该网站的任何人下载excel文件。 The excel file just stores data that I would like to make publicly available. excel文件仅存储我想公开获得的数据。 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. 我正在使用ruby on rails,想知道是否有一种简单的方法来存储我的excel电子表格(也许在Assets文件夹中?)并在我的网页上建立一个链接,单击该链接即可下载电子表格。 Thanks! 谢谢!

You can use CSV export (works with Excel pretty well) since Ruby has a well implemented CSV feature into the software. 您可以使用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

Also, you have to require it in your config/application.rb: 另外,您必须在config / application.rb中require它:

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 来源: GoRails(视频)RailsCasts

I figured it out by looking at a related post: How to give the xls file link in Ruby on Rails? 我通过查看相关文章找到了答案如何在Ruby on Rails中提供xls文件链接? and looking at the answer by hernanvicente 然后看着hernanvicente的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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