How to Download xlsx file using gem "axlsx" and "axlsx_rails" from rails 4 application using AJAX call?

1.2k Views Asked by At

I'm trying to download a xlsx file by using axlsx and axlsx_rails in a Rails 4 application.

My reports_controller:

def generate_report
@reports = Report.all
     respond_to do |format|
    format.xlsx {
      response.headers[
        'Content-Disposition'
      ] = "attachment; filename='items.xlsx'"
    }
end

Created generate_report.xlsx.axlsx file in app/views/reports/.

This is the code called when the download button is clicked:

$.ajax({
  type: 'GET',
  url: '/reports/generate_report',
  data: {
    user_id: user_id
  },
  success: function(response) {
    return console.log('file downloaded');
  }
});
1

There are 1 best solutions below

2
On

You could convert your xlsx file to Base64 and then send it.

Have a look at the send_data Rails method to send your Base64 worksheet.

Source: Rails - axlsx_rails, generating xlsx and sending via API