Rails--export csv

--controller

def export_agent_impressions

  export_start_time = Time.parse(params[:es_time]) + 7.hours

  export_end_time = Time.parse(params[:ee_time]) + 31.hours

  impressions = AgentImpression.where("created_at >= ? and created_at < ?", export_start_time, export_end_time).order("created_at desc")

  respond_to do |format|

    format.html

    format.csv {send_data agent_impressions_csv(impressions), filename: "agent_impressions_#{time}.csv"}

  end

end

 

--send_data csv data

def agent_impressions_csv(impressions)

  CSV.generate(headers: true) do |csv|

    columns = AgentImpression.column_names

    csv << columns

    impressions.each do |impression|

      csv << columns.map{|c| impression[c]}

    end

end

posted @ 2016-07-27 14:43  盖瑞  阅读(165)  评论(0编辑  收藏  举报