【问题标题】:ruby on rails export an excel data fileruby on rails 导出一个excel数据文件
【发布时间】:2015-07-28 07:03:10
【问题描述】:

我正在尝试设计一个网站,允许任何访问该网站的人下载 Excel 文件。 excel 文件只存储我想公开的数据。我正在使用 ruby​​ on rails,并且想知道是否有一种简单的方法来存储我的 excel 电子表格(可能在资产文件夹中?)并在我的网页上创建一个链接,单击该链接可以下载电子表格。 谢谢!

【问题讨论】:

    标签: html ruby-on-rails export-to-excel


    【解决方案1】:

    您可以使用 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 (Video)RailsCasts

    【讨论】:

    • 感谢您的回复。我仍然有点困惑(对不起,我是编码新手),我应该在哪里上传我想要导出的 csv?它不是根据活动记录制作的,而是我拥有并想要提供的文件。
    • Rails 依赖于 ActiveRecord(数据库),并带有某种方法的模型来传入。例如,如果您想包含具有用户名、位置等的记录,则需要将其存储在数据库。更新了更多来源
    • 所以没有办法将 excel 文件放在 rails 项目中的某个位置并在 html 中创建指向它的链接?
    • 不,目前,assets 文件夹将仅用于样式表、javascript 和图像(如果适用)。我通过Rails的官方文档研究,它只支持我上面提到的。
    【解决方案2】:

    我通过查看相关帖子找到了答案: How to give the xls file link in Ruby on Rails? 并查看 hernanvicente 的答案

    【讨论】:

      猜你喜欢
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多