24

I am using this Spreadsheet gem to export xls file.

I have the following codes in my controller:

def export
  @data = Data.all

  book = Spreadsheet::Workbook.new
  sheet = book.create_worksheet :name => "data"

  contruct_body(sheet, @data)

  book.write "data.xls"
end

In this way, I can fill in the data and save it in the root directory.

But I want to download it instead of save it. How could I modify the code so that the user prompted to select his local directory to save the file? (better if without saving a copy in the server side)

Please help!

PeterWong
  • 15,951
  • 9
  • 59
  • 68

4 Answers4

52

You can send it to the browser without saving it as a local file at all as follows

spreadsheet = StringIO.new 
book.write spreadsheet 
send_data spreadsheet.string, :filename => "yourfile.xls", :type =>  "application/vnd.ms-excel"
DanSingerman
  • 36,066
  • 13
  • 81
  • 92
2

You could try this code

book.write "data.xls"

send_file "/path/to/data.xls", :type => "application/vnd.ms-excel", :filename => "data.xls", :stream => false

# and then delete the file

File.delete("path/to/data.xls")

Passing :stream => false to send_file will instruct Rails to copy the entire file into memory before streaming, so using File.delete immediately after send_file would be fine since send_file returns immediately without waiting for the download to complete. Having said that, with very large files you may see some memory bottle necks depending on the amount of memory available.

HTH

Anand Shah
  • 14,575
  • 16
  • 72
  • 110
  • Bravo! In fact I just found out this exact same way in the afternoon but waiting for further test. Your answer gave me confidence so I think I don't need to worry anymore ^^ Thanks! – PeterWong Oct 29 '10 at 14:17
  • This does not seem to work anymore (I just inherited an app that uses this solution...). If I remove the `File.delete` part, this works. I trieed to delete the file in an after filter, but it does not work either. As i understand it, 'stream: false' is no longer an option for this method, and the file will NOT be cached... Any insight ? or should i use send_data ? – m_x Aug 13 '13 at 10:27
  • additional info : the `stream` option allegedly disapeared between rails v 3.0.9 and 3.1.0. – m_x Aug 13 '13 at 10:34
1

I understand this is insanely old, but I was looking for it so someone else might be.

This is the answer. (I'm using Sinatra.)

https://github.com/zdavatz/spreadsheet/issues/125#issuecomment-370157753

jkgaddis
  • 121
  • 3
0

The case happen on mybody. I used the ajax request by remote::true to export excel file, nothing display on browser without any error message on console. Delete the remote params from the form, it works well.