开发者

Calling def in Ruby for exporting CSV

开发者 https://www.devze.com 2023-01-23 10:53 出处:网络
I currently have some code which iv used to export a table from the data I have require \'fastercsv\' def dump_csv

I currently have some code which iv used to export a table from the data I have

require 'fastercsv'
def dump_csv
  @users = User.find(:all, :order => "lastname ASC")
  @outfile = "members_" + Time.now.strftime("%m-%d-%Y") + ".csv"

  csv_data = FasterCSV.generate do |csv|
    csv << [
    "Last Name",
    "First Name",
    "Username",
    "Email",
    "Company",
    "Phone",
    "Fax",
    "Address",
    "City",
    "State",
    "Zip Code"
    ]
    @users.each do |user|
      csv << [
      user.lastname,
      user.firstname,
      user.username,
      user.email,
      user.company,
      user.phone,
      user.fax,
      use开发者_开发知识库r.address + " " + user.cb_addresstwo,
      user.city,
      user.state,
      user.zip
      ]
    end
  end

  send_data csv_data,
    :type => 'text/csv; charset=iso-8859-1; header=present',
    :disposition => "attachment; filename=#{@outfile}"

  flash[:notice] = "Export complete!"
end

my question is how do I call it from my view and will this work with will_pagination. I know FasterCVS creates tables using the ActiveRecord so will_paginiation wont be of any use when trying to organize the table.


I don't understand why you are talking about will_paginate...

But if you want to send data or send a file from a controller, you should look at the methods send_data and send_file :

http://api.rubyonrails.org/classes/ActionController/Streaming.html


Thanks for your help. I saw your link and came up with this:

@lists = Project.find(:all, :order=> (params[:sort] + ' ' + params[:direction]), :conditions =>  ["name || description  LIKE ?", "%#{params[:selection]}%"])

    csv_string = FasterCSV.generate do |csv|
      csv << ["Status","Name","Summary","Description","Creator","Comment","Contact Information","Created Date","Updated Date"]

      @lists.each do |project|
        csv << [project.status, project.name, project.summary, project.description, project.creator, project.statusreason, project.contactinfo, project.created_at, project.updated_at]
      end
    end

    filename = Time.now.strftime("%Y%m%d") + ".csv"
    send_data(csv_string,
      :type => 'text/csv; charset=utf-8; header=present',
      :filename => filename)
  end
0

精彩评论

暂无评论...
验证码 换一张
取 消