ruby-on-rails - rails : Export arbitrary array to Excel using to_xls gem

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

我想通过以下方式将数据从 Rails 导出到 Excel:

  • 支持特殊字符(é、ô、ü 等)
  • 适用于所有版本的 Excel 2007+
  • 允许我在导出前添加计算列

  • 我正在考虑使用 to_xls gem,但不能让它在任意数组上工作(仅限 Active Record 对象)。

    文档说 gem 只是稍微面向导出 Active Record 集,并且它旨在将数组转换为 Excel,因此它必须是可能的。

    我认为问题在于它要求数组中的每个对象都响应 .attributes。我尝试了将虚拟属性添加到导出所基于的 Active Record 模型的方法,但似乎在调用 .attributes 时没有显示。

    我怎么能让这个工作? (或者您能否提出实现这些目标的替代方法?)

    最佳答案

    这应该适用于任意数组和 ActiveRecord 对象。显然, to_xls gem 支持通过 :columns 和 :headers 参数进行的所有自定义。

    require 'bundler/setup'
    require 'to_xls'
    
    class Person
      attr_reader :first_name, :last_name
    
      def initialize(first_name, last_name)
        @first_name = first_name
        @last_name  = last_name
      end
    
      def name
        "#{first_name} #{last_name}"
      end
    end
    
    array = [Person.new("Andrzej", "Krzywda"), Person.new("Derek", "Hill")]
    
    File.open("output.xls", "w") do |f|
      f.write(
        array.to_xls(
          :columns => [:first_name, :last_name, :name],
          :headers => ["First name", "Last name", "name"]
        )
      )
    end
    

    关于ruby-on-rails - rails : Export arbitrary array to Excel using to_xls gem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15600987/

    相关文章:

    ruby-on-rails - 为什么即使条件为真,拒绝也不能处理我的哈希?

    javascript - 提高创建 Excel 工作表的速度(以编程方式)

    php - 使用php将大量数据写入Excel没有内存限制错误

    css - 使用 HTML 页面的 css 格式显示标签导出到 Excel

    javascript - 将带分页的 PHP 表导出为 EXCEL、PDF、PRINTABLE

    ruby-on-rails - 使用 Devise after_sign_in_path_for 重定向循环

    ruby-on-rails - Sunspot Rails - 防止在保存时索引

    c# - 以编程方式将 Excel 电子表格中的数字字符串转换为实际数字

    ruby-on-rails - Authlogic Facebook 连接 Snafu

    ruby-on-rails - 包括 Controller 中的模块