• 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 "xEFxBBxBF"<<csv_res.force_encoding("ASCII-8BIT")
          end
        end
      end
    end
          end
        end
      end
    end
    

      

  • 相关阅读:
    windows 保留7天的文件
    同步
    bytes数据类型的转码问题:
    hashlib,logging,configparser模块
    面向对象 ---封装
    面向对象 -----多态
    面向对象 ---继承
    面向对象的命名空间与组合
    常用模块:
    匿名函数:
  • 原文地址:https://www.cnblogs.com/goody9807/p/4794567.html
Copyright © 2020-2023  润新知