Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Direct downloading a xls file without writing it to the directory by Spreadsheet gem

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!

like image 944
PeterWong Avatar asked Oct 29 '10 07:10

PeterWong


3 Answers

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"
like image 176
DanSingerman Avatar answered Oct 16 '22 13:10

DanSingerman


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

like image 29
Anand Shah Avatar answered Oct 16 '22 15:10

Anand Shah


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

like image 37
jkgaddis Avatar answered Oct 16 '22 13:10

jkgaddis