ruby-on-railsruby-on-rails-4export-to-excelxlsxaxlsx

Ruby on Rails: export xlsx export all html page instead the requested data


I'm using rails 4.2, and using gems axlsx and axlsx_rails I'm going to move to rails 5 soon but for now I use this version.

What I want: Export xlsx file from a query using axls_rails gem

What I get instead: it export the whole html file as data instead, see picture:

enter image description here

I followed 3 different guides as the git documentation exactly and already debugged it several times and didn't find the problem. Hope someone here can help me understand what causing it.

Gemfile:

gem 'rails', '4.2.11'

# import/export xlsx gems
gem 'write_xlsx'
gem 'rubyzip', '>= 1.2.1'
gem 'axlsx', git: 'https://github.com/randym/axlsx.git', ref: 'c8ac844'
gem 'axlsx_rails'

html file:

= link_to "<i class='icon icon-file-down'></i> Export</a></li>".html_safe, server_report_system_reports_path(format: :xlsx)

controller file:

def server_report
    organization_id = params[:organization_id]
    @accounts = Admin::Account.where("organization_id = ?", organization_id) unless organization_id.blank?
    @accounts_paginated = @accounts.paginate(per_page: 10, page: params[:page] || 1 )
   
    respond_to do |format|
      format.html
      format.xlsx {
        response.headers['Content-Disposition'] = 'attachment; filename="server_report.xlsx"'
      }
    end
  end

xlsx.axlsx file:

wb = xlsx_package.workbook
wb.add_worksheet(name: "Accounts") do |sheet|

  sheet.add_row ["Account id", "Member id", "Member name", "Member email"]
  @accounts_paginated.each do |account|
    account.members.each do |member|
      sheet.add_row [account.id, member.id, member.name, member.email]
    end
  end
end

EDIT: I tried to call a different def called export and try to see if there's a problem with respond_to and use another query but it also did the same

I also tried to write in format.xlsx this line but still nothing changed:

EDIT 2: I tried to render in respond_to the file instead in axlsx.xlsx file in format.xlsx but I got the same result

response.headers['Content-Disposition'] = 'attachment; filename="server_report.xlsx"'


Solution

  • I found the problem. I added layout: false when I render the xlsx file in the controller and it worked