rails 实现导出为excel

用ruby的csv库,必须将之引入  require ‘csv’

 

控制器

 def export_excel
    content_type = if request.user_agent =~ /windows/i
      'application/vnd.ms-excel'
    else
      'text/csv'
    end
 
    CSV::Writer.generate(output = "") do |csv|
    
      (SearchLogRecord.find :all).each do |record|
          csv << [record.created_at.to_s(:db),record.ip,record.search_domain,record.search_url,record.our_url,record.search_words]
      end
    end
    send_data(output, :type=> content_type, :filename => "#{Time.now.strftime('%Y%m%d%H%M%S')}.csv")
  end

你可能感兴趣的:(windows,Excel,Ruby,Rails)