在模板xls中下载数据

时间:2018-04-04 18:34:29

标签: ruby-on-rails xls

我想知道如何重定向到模板,并使用此模板下载,我尝试了一些东西,使用我在pdf中的模板,但它无法正常工作。 这是我到底有多远:

def download
    @reversals = Reversal.where("created_at >= ? and created_at <= ?", params[:start_date], params[:end_date])
    respond_to do |format|
      format.xls {           
           send_data(:filename => 'estornos.xls', :disposition => 'attachment', :action => :index, :layout => false, :template => 'reversals/download.xls.erb', locals: {:reversals => @reversals})
        }
    end
 end

我在这里打电话给我:

<%= form_for :reversal, method: :post, url: download_reversals_path do %>
        <%= date_select "reversal", "start_date" %>
        <%= date_select "reversal", "end_date" %>
    <%= submit_tag 'Download' %>
<% end %>

这是我的路线:

resources :reversals do
    collection do
      post 'download', :defaults => { :format => 'xls', :template => 'download.xls.erb'}
    end
  end

我已经将xls的类型放在mime_type中。我已经安装了模板,但我无法连接这两个。使用该方法的模板,它们具有相同的名称。

1 个答案:

答案 0 :(得分:0)

经过多次测试和时间后,我发现了怎么做:

路线:

post 'reversals/download', to: "reversals#download_pdf", as: 'download', format: 'xls'

控制器:

def download_pdf
    report_start_date= build_date_from_params("start_date", params[:reversal])
    report_end_date= build_date_from_params("end_date", params[:reversal])
    @reversals = Reversal.all.where("created_at >= ? and created_at <= ? or created_at = ? and created_at = ? ", report_start_date, report_end_date, report_start_date, report_end_date)
    @start_date = report_start_date
    @end_date = report_end_date
    respond_to do |format|
      format.html
      format.xls {
        response.headers['Content-Disposition'] = 'attachment; filename=" estornos-' + (Time.now).to_s + '.xls"'
        render "download.xls.erb"
       }
    end
end
def build_date_from_params(field_name, params)
      Date.new(params["#{field_name.to_s}(1i)"].to_i, 
           params["#{field_name.to_s}(2i)"].to_i, 
           params["#{field_name.to_s}(3i)"].to_i)
end

mime_types:

Mime::Type.register "application/xls", :xls

在我的索引视图中

<%= form_for :reversal, method: :post, url: download_path, format: 'xlsx' do %>
<table>
  <tr>
    <td>DATA DE LANÇAMENTO INICIAL:</td>
    <td></td>
    <td><%= date_select "reversal", "start_date" %></td>
    <td rowspan="2" align="center"><%= submit_tag 'Download xlsx', class: 'btn btn-secundary' %></td>
  </tr>
  <tr>
    <td>DATA DE LANÇAMENTO FINAL:</td>
    <td></td>
    <td><%= date_select "reversal", "end_date" %></td>
  </tr>
</table>
<% end %>

如果你试图下载到excel,格式xls不起作用,它必须是xlsx,它只是在mime类型中注册xlsx格式,并在视图中传递格式:xlsx,in路由tb创建或更改格式为xlsx的路由。不要忘记使用nameoffunction.xlsx.erb创建视图。