0

Hi I'm having trouble downloading multiple files with axlsx. The problem is I'm sending an array of Id's to the controller and asking it to download the report using the render command. It raises an AbstractController::DoubleRenderError. I was thinking of overriding the error but realized it's a bad idea, I don't know what else to do... Any suggestions? Thanks.

My controller code looks like this:

  def download_report
    params[:user_id].each do |user_id|
      @report = Report.find_by(:user_id => user_id)
      render :xlsx => "download_report", :filename => "#{@report.user.last_name}.xlsx"
    end
  end

My axlsx template:

  wb = xlsx_package.workbook
  wb.add_worksheet(name: "Reports") do |sheet|
    wb.styles do |s|
      # template code
    end
  end

1 Answers1

0

It is the built in expectation of Rails that you would call render once per request. And, the browser is going to expect one response per request. So, you are going to have to do something else!

You can use render_to_string, and combine the results into a zip file, serving that. See the bottom of this response.

Or, you could create a single spreadsheet and have each user's report show up on their own worksheet.

Or, on the client side, you could use javascript to request each spreadsheet and download each one separately.

The zip one would be something like this code, which uses render_to_string, rubyzip, and send_data:

def download_report
  compressed_filestream = Zip::ZipOutputStream.write_buffer do |zos|
    params[:user_id].each do |user_id|
      @report = Report.find_by(:user_id => user_id)
      content = render_to_string :xlsx => "download_report", :filename => "#{@report.user.last_name}.xlsx"
      zos.put_next_entry("user_#{user_id}.xlsx")
      zos.print content
    end
  end
  compressed_filestream.rewind
  send_data compressed_filestream.read, :filename => 'download_report.zip', :type => "application/zip"
end

Axlsx requires rubyzip, so you should have it already. And you probably want to lookup each user and use their name for the spreadsheet, unless you have it otherwise.

noel
  • 2,095
  • 14
  • 14
  • Thanks for your comment I am very optimistic it can work. I did as you said and now I am getting an uninitialized constant Zip::ZipOutputStream error. Do you know why that is? I have searched online and found that rubyzip 1.0.0 produces this error, and also to use :require 'zip/zip' or require 'zip'. None of this has helped. I feel it is an easy fix, just cant seem to find it. Im new in rails. Thanks in advance. – Carlos Alberto Salgado Hazbun Aug 29 '14 at 06:20
  • Take a look in your lock file and let me know what axlsx and rubyzip versions are there. Also, what do you have in your Gemfile? – noel Sep 02 '14 at 16:31