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

PeterWong picture PeterWong · Oct 29, 2010 · Viewed 14.4k times · Source

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!

Answer

DanSingerman picture DanSingerman · Nov 2, 2010

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"