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

后端 未结 4 685
天命终不由人
天命终不由人 2020-12-13 14:29

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:         


        
相关标签:
4条回答
  • 2020-12-13 14:47

    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.

    0 讨论(0)
  • 2020-12-13 14:57

    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"
    
    0 讨论(0)
  • 2020-12-13 14:58

    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

    0 讨论(0)
  • 2020-12-13 15:02

    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

    0 讨论(0)
提交回复
热议问题