rails - 保存csv

访问量: 195

看下面的例子即可

需要注意的是,身份证号在csv中不带引号,所以Excel会把 > 15位的数字显示成 ### , 所以我们需要把它特殊处理一下 ,价格\t

  def download_csv
    require 'csv'
    # 这个是获得数据的方法
    @members = get_members params

    headers = ['邮箱','电话','姓名', '性别', '身份证号', '注册时间',  '自身邀请码', '注册邀请码', '邀请会员人数', '所属家族']
    file = CSV.generate do |csv|
      # 先放 header
      csv << headers
      # 再放  csv 的内容
      @members.each_with_index do |member, index|
        id_card_approval = IdCardApproval.where('member_id = ? and is_passed = ?', member.id, true).first
        row = [member.email,
                "#{member.mobile}\t",
                id_card_approval.try(:name),
                id_card_approval.try(:gender),
                "#{id_card_approval.try(:number)}\t", # \t 为了让excel不再把15位以上数字显示成###
                member.created_at.strftime("%Y-%m-%d %H:%M:%S"),
                member.invitation_code,
                member.inviter_code,
                member.invited_new_members_count,
                member.family]

        Rails.logger.info "== row: #{row.inspect}"
        csv << row 
      end 
    end 
    send_data file.encode("gbk", "utf-8", {invalid: :replace, undef: :replace, replace: '?'}), :type => 'text/csv; charset=gbk; header=present', , :disposition => "attachment;filename=团队成员列表.csv"
  end 

订阅/RSS Feed

Subscribe

分类/category