gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:10:39 25 4
gpt4 key购买 nike

我想通过以下方式将数据从 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com