Rails中用CSV导出中文真心有技巧
require 'csv' class PartRequestsController < ApplicationController def render_csv_header(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 end def index @part_requests = PartRequest.where(:status => params[:status]).order('id DESC') @status = params[:status] respond_to do |format| format.html # index.html.erb format.json { render json: @part_requests } format.csv do render_csv_header 'Part_Request_Report' csv_res = CSV.generate do |csv| csv << PartRequest.new.attributes.keys @part_requests.each do |o| o.part_request_details.each do |d| csv << o.attributes.values end end end send_data "\xEF\xBB\xBF"<<csv_res.force_encoding("ASCII-8BIT") end end end end end end end end