require 'csv' require 'nkf' csv_title = ["id", "用户名称", "用户电话","最后登录时间", "用户部门", "所属高校","课程数量", "高校省份", "高校城市", "高校地址", "实训总数"] school_ids = School.select(:id, :province).where(province: ["安徽","江苏"]).pluck(:id) user_items = [] an_items = [] j_items = [] users = UserExtension.where(school_id: school_ids, identity: :teacher).includes(:user,:department, school: :courses) users.each_with_index do |u, index| user = u.user school = u.school course_count = school.courses.size shixun = SchoolReport.select(:school_id, :shixun_evaluate_count).find_by(school_id: u.school_id).try(:shixun_evaluate_count) item = [index+1, user.try(:show_real_name), user.try(:phone), user.try(:last_login_on), u&.department.try(:name), school.try(:name),course_count, school.try(:province), school.try(:city), school.try(:address), shixun] if u.school.try(:province) == "安徽" an_items.push(item) else j_items.push(item) end end user_items = an_items + j_items csv_string = CSV.generate(headers: true) do |csv| csv << csv_title user_items.each do |i| csv << i end end fh = File.new("public/teachers.csv", "wb") fh.puts NKF.nkf("-wL",csv_string) fh.close