3
Rails 4.2
RubyXL

I am using the RubyXL to create a workbook. I can write it disk with:

workbook.write("path/to/desired/Excel/file.xlsx")

and then download it with something like this:

send_file(workbook.write("path/to/desired/Excel/file.xlsx"), options = {:filename => 'myworkbook.xlsx', :disposition => 'attachment'})

Any suggestions on how to download it without having to save it to the server first?

EastsideDev
  • 6,257
  • 9
  • 59
  • 116

2 Answers2

11

You may convert workbook directly to a string:

def get_worksheet_as_string
  workbook = RubyXL::Workbook.new
  # Fill workbook here or leave as is to download empty
  send_data workbook.stream.string, filename: "myworkbook.xlsx",
                                    disposition: 'attachment'
end
Mareq
  • 1,311
  • 2
  • 12
  • 15
  • It did not work. The error message is that I am getting a nil in the stream. When I save it to disk, it works fine. – EastsideDev Jan 02 '16 at 13:51
  • 1
    @EastsideDeveloper It is working in my code, I don't know what difference may cause such behavior. Can you try to replace `string` with `read`? It should return this same result, but I'm guessing what is wrong... – Mareq Jan 02 '16 at 16:55
  • Updated my answer with method I tried a while ago. In this state it works as expected. You can try this and then inspect, what modification of the workbook means that it stop working. – Mareq Jan 02 '16 at 17:13
  • Nice! This should be in the docs. I didn't know you needed to convert to string. – Petercopter Mar 28 '17 at 17:21
1

If you're working in Sinatra:

get '/download-xlsx/?' do
    content_type 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    attachment(filename = "filename.xlsx", disposition = :attachment)

    workbook = RubyXL::Workbook.new

    # Fill the workbook with data

    workbook.stream
end

Thought it might be helpful for those working in Sinatra!

Ayer
  • 120
  • 2
  • 6