我正在使用CSV类将结果导出到csv。我现在正在使用它,但它只将我的搜索查询导出为CSV,而不是结果(显示在我的'show;页面上)。
search.rb
class Search < ActiveRecord::Base
def to_xls(options = {})
{
"Id" => id.to_s,
"firstname" => firstname,
"surname" => surname,
"officenumber" => officenumber,
"department" => department,
"division" => division,
"address" => address,
"notes" => notes
}
end
end
searches_controller.rb
def show
@search = Search.find(params[:id])
respond_to do |format|
format.html
format.xls { send_data @searches.to_xls, content_type: 'application/vnd.ms-excel', filename: 'search.xls' }
end
end
mime_types.rb
Mime::Type.register "application/vnd.ms-excel", :xls
答案 0 :(得分:2)
你应该试试这个,
def self.to_xls(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |product|
csv << product.attributes.values_at(*column_names)
end
end
end
链接应该像<%= link_to "Excel", your_path(format: "xls") %>
您可以找到完整的流程here来实现它。