How to export and render for downloading an Excel file

30 views
Skip to first unread message

Serguei Cambour

unread,
May 7, 2019, 1:30:25 PM5/7/19
to spreadsheet
I didn't find any examples of how it is possible (if it is) to send a generated Excel file based on some ActiveRecord collection.
For a PDF file generated with Prawn, I could do that as follows:

# in a controller


def show
 
@operation = @account.operations.find(params[:id])
  report    
= OperationReport.new
  output    
= report.to_pdf(@operation)
  respond_to
do |format|
    format
.pdf do
      send_data output
, type: :pdf, disposition: "inline"
   
end
 
end
end


Any ideas for Excel ? Thank you.

Serguei Cambour

unread,
May 8, 2019, 5:02:35 PM5/8/19
to spreadsheet
I figured out how to do that:

# comments_controller.rb


def index
     
@comments = @commentable.comments
      book
= ExcelReport.new(@comments).export
      file_contents
= StringIO.new
      book
.write file_contents
      respond_to
do |format|
        format
.xls do
          send_data file_contents
.string, type: 'application/vnd.ms-excel', filename: 'comments.xls'
       
end
     
end
   
end



You should also register :xls as MIME type in initializers/mime_type.rb file as follows:

Mime::Type.register "application/vnd.ms-excel", :xls



Hope this helps.

Serguei Cambour

unread,
May 8, 2019, 5:05:49 PM5/8/19
to spreadsheet
ExcelReport.new is just a Ruby class where I create an Excel file using standard methods provided by spreadsheet gem to write to rows, columns, etc. and the export method just returns an instance of Spreadsheet::Workbook:

def export
    book = Spreadsheet::Workbook.new
   ....# your sheet design come here

    book
  end

On Tuesday, 7 May 2019 19:30:25 UTC+2, Serguei Cambour wrote:

Zeno Davatz

unread,
May 9, 2019, 1:59:53 AM5/9/19
to rubyspr...@googlegroups.com
Dear Serguei

Great, thanks for sharing!

Best
Zeno
Reply all
Reply to author
Forward
0 new messages