Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

After some experiments with respond_to I move .xlsx generation logic to view helper.

So I have included BasicReportHelper in controller.

basic_report_helper.rb

module BasicReportsHelper
    def generate_basic_report(filename)
        p = Axlsx::Package.new
        wb = p.workbook
        wb.add_worksheet(:name => "Basic Worksheet") do |sheet|
          # Drawing here          
        end
        p.serialize filename 
      end
end

Changed post call to /basic_report_post.json and changed action to

def basic_report_post
    @config = params[:config]
    @data = params[:data]
    @filename = "#{Rails.root}/public/test.xlsx"
    generate_basic_report(@filename)
    respond_to do |format|
       format.json {
         render json: {name: @filename}
       }          
    end
  end
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top