Search code examples
ruby-on-railsjsonexport-to-excelaxlsx

Axlsx Rails. Generate .xlsx file and respond filename as json/html


I am generating xlsx files with axlsx_rails gem.

After collecting user input I am posting data to /basic_report_post.xlsx

Controller action looks like

def basic_report_post
    @config = params[:config]
    @data = params[:data]
    @filename = "#{Rails.root}/public/test.xlsx"

    respond_to do |format|
      format.xlsx {
        render xlsx: 'basic_report_post'
      }
    end
  end

View file for this action basic_report_post.xlsx.axlsx

wb = xlsx_package.workbook    
wb.add_worksheet(name: 'Data1') do |s|    
# Drawing columns    
end
xlsx_package.serialize @filename

My problem is that I am getting response data(in post success action) that is raw .xlsx file. But I need somehow respond @filename (format json/html) to download it after.


Solution

  • It is possible to use the axlsx_rails template renderer to create a string and save it to file:

    def basic_report_post
      @config = params[:config]
      @data = params[:data]
      @filename = "#{Rails.root}/public/test.xlsx"
      File.open(@filename, 'w') do |f|
        f.write render_to_string(handlers: [:axlsx], formats: [:xlsx], template: 'path/to/template')
      end
      render json: {name: @filename}
    end
    

    Then you can use the template to serve the file directly if need be.