Search code examples
ruby-on-railssidekiqaxlsx

Save xlsx file to disk in Sidekiq as background


I am trying to generate excel file in background by using axlsx and save it (Rails4.2). In GitHub page of axlsx, it says As of Rails 4.1 you must use render_to_string to render a mail attachment. However, it throws me a error NoMethodError: undefined method 'render_to_string' for #<CreateExcelSheetWorker:0x007fbccf51db30>

My worker class:

class CreateExcelSheetWorker
  include Sidekiq::Worker
  include Sidetiq::Schedulable

  recurrence { daily }

  def perform()
    model = SomeModel.where(wanted: true).order(started_at: :desc)
    xlsx = render_to_string handlers: [:axlsx], formats: [:xlsx], template: "template/file", locals: {model: model}
    path = "/tmp/a.xlsx"
    File.open(path, "w+") do |f|
      f.write(xlsx)
    end
  end
end

I cannot figure out how to fix this, any help appreciated.


Solution

  • That render_to_string comment is for usage of the gem in actionmailers. Outside of any kind of view context, you'll have to use xlsx builder api directly. Something like this:

    package = Axlsx::Package.new do |p|
      p.workbook.add_worksheet(name: "Summary") do |sheet|
        sheet.add_row ["foo", 1]
      end
    end
    
    File.write(filename, package.to_stream.read)