只需两步,rails支持CSV格式导出
一、Controller最上方添加 require 'csv'
二、方法里面添加
format.csv do csv_string = CSV.generate do |csv| csv << ["Name", "Created At"] @people.each do |person| csv << [person.name, person.created_at] end end render :text => csv_string end
最终代码:
require 'csv' class PeopleController < ApplicationController def index @people = Person.all respond_to do |format| format.html # index.html.erb # 对应url http://localhost:222/people.json format.json { render json: @people } # 对应url http://localhost:222/people.xml format.xml { render :xml => @people} format.atom { @feed_title = "My event list" } # index.atom.builder # 添加csv格式 format.csv do csv_string = CSV.generate do |csv| csv << ["Name", "Created At"] @people.each do |person| csv << [person.name, person.created_at] end end render :text => csv_string end end end
最后浏览器http://localhost:3000/people.csv 不过用excel打开UTF-8格式的csv汉字会显示乱码,需要转换为GBK