in rails, how to return records as a csv file

后端 未结 10 1213
醉话见心
醉话见心 2020-11-28 05:02

I have a simple database table called \"Entries\":

class CreateEntries < ActiveRecord::Migration
  def self.up
    create_table :entries do |t|
      t.st         


        
相关标签:
10条回答
  • 2020-11-28 05:36

    The following approached worked well for my case and causes the browser to open the appropriate application for the CSV type after downloading.

    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
    
    0 讨论(0)
  • 2020-11-28 05:38

    There is a plugin called FasterCSV that handles this wonderfully.

    0 讨论(0)
  • 2020-11-28 05:39

    If you're simply wanting to get the csv database yourself from the console you can do so in a few lines

    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(""))}
    
    0 讨论(0)
  • 2020-11-28 05:44

    You need to set the Content-Type header in your response, then send the data. Content_Type: application/vnd.ms-excel should do the trick.

    You may also want to set the Content-Disposition header so that it looks like an Excel document, and the browser picks a reasonable default file name; that's something like Content-Disposition: attachment; filename="#{suggested_name}.xls"

    I suggest using the fastercsv ruby gem to generate your CSV, but there's also a builtin csv. The fastercsv sample code (from the gem's documentation) looks like this:

    csv_string = FasterCSV.generate do |csv|
      csv << ["row", "of", "CSV", "data"]
      csv << ["another", "row"]
    # ...
    end
    
    0 讨论(0)
提交回复
热议问题