替换 `to_xls` gem 以生成 'xlsx' 文件

问题描述 投票:0回答:0

我有一个 Rails 应用程序,我在其中使用

to_xls
gem 生成“xls”文件,但现在我想生成“xlsx”文件。

所以我想问一下,是否有一种方法可以仅使用

to_xls
gem 生成“xlsx”文件?如果没有,其他什么 gem 应该是生成“xlsx”文件的最佳选择? (我在想也许
roo
axlsx
gem 应该适合这个。)

我附上了我当前用于生成“xls”文件的代码,因为我只需要更新此代码

class ToXmlResponder < Dossier::Responder
  def to_xls
    set_content_disposition!
    controller.response_body = to_xls_raw
  end

  def to_xls_raw
    book = Spreadsheet::Workbook.new

    xls_content.write_book(book)
    xls_metadata.write_book(book)

    response = StringIO.new
    book.write(response)
    response.string.force_encoding('binary')
  end

  def xls_content
    xls_opts = collection_and_headers(resource.raw_results.arrays)
    headers = xls_opts[1]
    items = resource.results.hashes.map{|h| Hashie::Mash.new(h) }
    columns = resource.raw_results.headers

    ToXls::Writer.new(
      items,
      :columns => columns,
      :headers => headers,
    )
  end

  def xls_metadata
    ToXls::Writer.new(
      [
        {
          :name => I18n.t('report_info.start_date'),
          :value => resource.start_date_in_timezone(resource.user_time_zone).to_s
        },
        {
          :name => I18n.t('report_info.end_date'),
          :value => resource.end_date_in_timezone(resource.user_time_zone).to_s
        },
        {
          :name => I18n.t('report_info.export_by'),
          :value => resource.user.username.to_s
        },
        {
          :name => I18n.t('report_info.export_date'),
          :value => Time.now.in_time_zone(resource.user_time_zone).to_s
        }
      ].reject{|r| r[:value].empty? }.map{|r| Hashie::Mash.new(r) },
      :name => I18n.t('report_info.sheet_name'),
      :columns => %i[name value]
    )
  end
end

如果有人愿意帮助我解决这个问题,我将非常感激,为我指出正确的方向,比如我应该从哪里开始。 请通过上面的代码片段帮助我,让我知道如何更新它以生成“xlsx”文件而不是🙏

ruby-on-rails excel ruby xlsx
© www.soinside.com 2019 - 2024. All rights reserved.