我在Rails应用程序中包含CSV导入功能。但是我面临的问题是,如果任何行业的标题中都包含撇号,那么它在CSV中就会显得很奇怪。如何添加meta http-equiv =“ Content-Type” content =“ text / html; charset = ISO-8859-1”,以便CSV包含撇号。
CSV_HEADER = %w[title role team]
def self.to_csv
CSV.generate do |csv|
csv << CSV_HEADER
all.each do |industry|
csv << [
industry.title,
industry.role,
industry.team
]
end
end
end
<%= link_to "Download CSV", admin_path(@industry, :format => :csv, :filterrific => @filterrific.to_hash), class: "btn btn-primary btn-2x" %>
控制器动作
def application
require 'csv'
add_breadcrumb "Admin", :main_admin_path
add_breadcrumb "Industrial Applications"
@filterrific = initialize_filterrific(
Industry,
params[:filterrific],
select_options: {
with_status: Industry.options_for_status
}
) or return
@industries = @filterrific.find
@industries = @industries.paginate(:page => params[:page], :per_page => 10) unless request.format == 'csv' #does pagination if not csv format
respond_to do |format|
format.html
format.js
format.csv { send_data @industries.to_csv, :type => 'text/csv; charset=iso-8859-1; header=present' }
end
rescue ActiveRecord::RecordNotFound => e
puts "Had to reset filterrific params: #{ e.message }"
redirect_to(reset_filterrific_url(format: :html)) and return
end
答案 0 :(得分:0)
BOM(字节顺序标记)的概念用于解决此问题。
format.csv { send_data "\uFEFF" + @industries.to_csv, type: :csv }