0

I've been trying to generate an XLSX file in my app. I'm using the gem 'acts_as_xlsx'.

The problem is that the document is generated in the background, and I don't want to render a view. It's a script that should return the XLSX file.

I'm trying to do something like:

file = File.open("report.xlsx", relation.to_xlsx, type: "application/vnd.openxmlformates-officedocument.spreadsheetml.sheet")

This returns an error as the second argument of the File.open must be a string.

Thanks in advance!

hcarreras
  • 4,442
  • 2
  • 23
  • 32

1 Answers1

1

to_xlsx should return the Axlsx package. The package will save itself to a file:

relation.to_xlsx.serialize("report.xlsx")

However, if you are emailing it, all you need is to place that as the attachment. You don't need to save it as a file:

class UserMailer < ActionMailer::Base
  def export(users)
    content = User.to_xlsx(data: users).to_stream.string
    attachments["Users.xlsx"] = {mime_type: Mime::XLSX, content: content}
    ...
  end
end

Also, you'll notice above, acts_as_xlsx registers Mime::XLSX for you. So you can use that instead of the long mime string.

noel
  • 2,095
  • 14
  • 14
  • Thanks. I wasn't using any controller or mailer, I was generating a file in a script. It helped. Thanks. Finally my code was: relation_xlsx = relation.to_xlsx; relation_xlsx.serialize("report.xlsx"); serialized_relation = relation_xlsx.to_stream; file = File.open('report_streamed.xlsx', 'w'); file.write(serialized_relation.read) It is necessary to separate the methods .to_xlsx and .serialize because serialize returns true, so if afterwards you try: relation_xlsx.to_stream it will return "Undefined method to_stream for true:TrueClass – hcarreras Jul 14 '14 at 09:34