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

一世执手 提交于 2020-01-02 10:00:24

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/23689472/axlsx-rails-generate-xlsx-file-and-respond-filename-as-json-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!