繁体   English   中英

如何动态生成url(用于生成xls报告)?

[英]How I can dynamically generate url ( for generating xls report )?

你好!

我遇到了麻烦:我正在按日期搜索报告,并且在html视图中一切正常,但是在渲染xls视图时会出现错误,因为它没有收到参数,因此我需要在URL中将它们传递给xls link_to发电机。

我的控制器:

def show
  @website = Website.find(params[:id])
  if params[:report] && params[:report][:start_date] && params[:report][:end_date]
    #search_by_created_at
    @performance_reports = @website.performance_reports.where("created_at between ? and ?", params[:report][:start_date].to_date, params[:report][:end_date].to_date)
  else
    @performance_reports = @website.performance_reports
  end
  respond_to do |format|
    format.html # index.html.erb
    format.xls
    format.xml  { render :xml => @performance_reports }
  end
end

和我生成的网址看起来像:

 http://127.0.0.1:3000/websites/25/performance_reports/show?utf8=%E2%9C%93&report[end_date]=07%2F09%2F2012&report[start_date]=04%2F09%2F2012&commit=Run+Report

我的xls网址是这样生成的:

 <%= link_to url_for(:format => 'xls')  do%>
   <%= image_tag("excel.png", :id => "analytics",:size => '21x23')%> <b>Export</b>
 <% end %>

结果:

http://127.0.0.1:3000/websites/25/performance_reports/show

任何帮助将不胜感激。

xls in默认情况下不可用。

添加:

gem "spreadsheet"
gem "to_xls", :git => "https://github.com/dblock/to_xls.git", :branch => "to-xls-on-models"

通过添加以下内容,在config/initializers/mime_types.rb注册Excel MIME类型:

Mime::Type.register "application/vnd.ms-excel", :xls

添加一个as_xls方法以为要导出的字段建模。 例如,对于User模型,您可能具有:

def as_xls(options = {})
  {
      "Id" => id.to_s,
      "Name" => name,
      "E-Mail" => email,
      "Joined" => created_at,
      "Last Signed In" => last_sign_in_at,
      "Sign In Count" => sign_in_count
  }
end

向控制器添加代码:

def index
  @users = User.all
  respond_to do |format|
    format.html
    format.xls { send_data @users.to_xls, content_type: 'application/vnd.ms-excel', filename: 'users.xls' }
  end
end

提供链接:

= link_to 'Export', users_path(request.parameters.merge({:format => :xls}))

所有代码都应进行测试。 您可以执行以下操作:

describe "GET index.xls" do
  it "creates an Excel spreadsheet with all users" do      
    user = Fabricate :user
    get :index, :format => :xls
    response.headers['Content-Type'].should == "application/vnd.ms-excel"
    s = Spreadsheet.open(StringIO.new(response.body))
    s.worksheets.count.should == 1
    w = s.worksheet(0)
    w.should_not be_nil
    w.row(0)[0].should == "Id"
    w.row(1)[0].should == user.id.to_s
    w.row(0)[1].should == "Name"
    w.row(1)[1].should == user.name
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM