代码之家  ›  专栏  ›  技术社区  ›  Eric

在Rails中,如何将记录作为csv文件返回

  •  52
  • Eric  · 技术社区  · 16 年前

    我有一个称为“entries”的简单数据库表:

    class CreateEntries < ActiveRecord::Migration
      def self.up
        create_table :entries do |t|
          t.string :firstName
          t.string :lastName
          #etc.
          t.timestamps
        end
      end
    
      def self.down
        drop_table :entries
      end
    end
    

    如何编写一个将条目表的内容作为csv文件返回的处理程序(理想情况下,它将在Excel中自动打开)?

    class EntriesController < ApplicationController
    
      def getcsv
        @entries = Entry.find( :all )
    
        # ??? NOW WHAT ????
    
      end
    
    end
    
    10 回复  |  直到 16 年前
        1
  •  22
  •   Brian    16 年前

        2
  •  87
  •   Clinton Dreisbach    16 年前

    FasterCSV

    def render_csv(filename = nil)
      filename ||= params[:action]
      filename += '.csv'
    
      if request.env['HTTP_USER_AGENT'] =~ /msie/i
        headers['Pragma'] = 'public'
        headers["Content-type"] = "text/plain" 
        headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'
        headers['Content-Disposition'] = "attachment; filename=\"#{filename}\"" 
        headers['Expires'] = "0" 
      else
        headers["Content-Type"] ||= 'text/csv'
        headers["Content-Disposition"] = "attachment; filename=\"#{filename}\"" 
      end
    
      render :layout => false
    end
    

    respond_to do |wants|
      wants.csv do
        render_csv("users-#{Time.now.strftime("%Y%m%d")}")
      end
    end
    

    generate_csv

    UserID,Email,Password,ActivationURL,Messages
    <%= generate_csv do |csv|
      @users.each do |user|
        csv << [ user[:id], user[:email], user[:password], user[:url], user[:message] ]
      end
    end %>
    
        3
  •  24
  •   Eric    16 年前

    this wiki page

    require 'fastercsv'
    
    class EntriesController < ApplicationController
    
      def getcsv
          entries = Entry.find(:all)
          csv_string = FasterCSV.generate do |csv| 
                csv << ["first","last"]
                entries.each do |e|
                  csv << [e.firstName,e.lastName]
                end
              end
              send_data csv_string, :type => "text/plain", 
               :filename=>"entries.csv",
               :disposition => 'attachment'
    
      end
    
    
    end
    
        4
  •  24
  •   rwc9u    16 年前

    require "csv"
    

    Ryan Bate's Advanced Search Form

      def show
        @advertiser_search = AdvertiserSearch.find(params[:id])
        @advertisers = @advertiser_search.search(params[:page])
        respond_to do |format|
          format.html # show.html.erb
          format.csv  # show.csv.erb
        end
      end
    

    <%- headers = ["Id", "Name", "Account Number", "Publisher", "Product Name", "Status"] -%>
    <%= CSV.generate_line headers %>
    <%- @advertiser_search.advertisers.each do |advertiser| -%>
    <%- advertiser.subscriptions.each do |subscription| -%>
    <%- row = [ advertiser.id,
                advertiser.name,
                advertiser.external_id,
                advertiser.publisher.name,
                publisher_product_name(subscription),
                subscription.state ] -%>
    <%=   CSV.generate_line row %>
    <%- end -%>
    <%- end -%>
    

    <%= link_to "Export Report", formatted_advertiser_search_path(@advertiser_search, :csv) %>
    
        5
  •  7
  •   kch    16 年前

    FasterCSV

    gem install fastercsv
    gem install spreadsheet-excel
    

    FasterCSV.generate(:col_sep => ";", :row_sep => "\r\n") { |csv| ... }
    

    CSV_FIELDS = %w[ title created_at etc ]
    FasterCSV.generate do |csv|
      Entry.all.map { |r| CSV_FIELDS.map { |m| r.send m }  }.each { |row| csv << row }
    end
    
        6
  •  2
  •   JasonTrue    16 年前

    csv_string = FasterCSV.generate do |csv|
      csv << ["row", "of", "CSV", "data"]
      csv << ["another", "row"]
    # ...
    end
    
        7
  •  2
  •   rantler    12 年前

    def index
      respond_to do |format|
        format.csv { return index_csv }
      end
    end
    
    def index_csv
      send_data(
        method_that_returns_csv_data(...),
        :type => 'text/csv',
        :filename => 'export.csv',
        :disposition => 'attachment'
      )
    end
    
        8
  •  1
  •   Henry Jacob    12 年前
        10
  •  0
  •   boulder_ruby    11 年前

    tags = [Model.column_names]
    rows = tags + Model.all.map(&:attributes).map(&:to_a).map { |m| m.inject([]) { |data, pair| data << pair.last } }
    File.open("ss.csv", "w") {|f| f.write(rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join(""))}