中文乱码问题

中文乱码问题
解決方式跟 wordpress 一樣,需要傳送 ‘SET NAMES …’ 給 MySQL。以 utf-8 為例,就是 ‘SET NAMES utf8′。
(如果您也是使用MySQL5.0.24,可以使用這個方法。MySQL 4.0則不支援傳送語系設定字串,所以會擲回錯誤。其他版本請自己試試囉!)
打開 application.rb,在 class ApplicationController 中增加 一個函式 configure_charsets,在函式內傳送這個語系字串,並於 before_filter 呼叫這個函式。
改完後 application.rb 類似這樣:
class ApplicationController < ActionController::Base
   before_filter :configure_charsets
       def configure_charsets
       suppress(ActiveRecord::StatementInvalid) do
           ActiveRecord::Base.connection.execute 'SET NAMES utf8'
       end
   end
end
某些情況下,configure_charsets 中還需要加上下面兩行:
@headers["Content-Type"] = "text/html; charset=utf-8"
@response.headers["Content-Type"] = "text/html; charset=utf-8"
但是比較建議在 layout 裡指定:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
不要忘了放在 title 前面。
以上是在网上查到的,终于解决了我的问题(在导出Excel是中文不能正确显示)
def self.download
    workbook=Excel.new("#{RAILS_ROOT}/public/report/publisher_#{Time.now.strftime('%Y-%m-%d %H-%M')}.xls")
    format=Format.new()
    format.color='green'
    format.bold=true
    worksheet=workbook.add_worksheet("Report of #{1.day.ago.strftime('%Y-%m-%d')}")
    worksheet.write(0,0,Iconv.conv("gbk","utf-8",'楼宇表'),format)
    worksheet.write(1, 0, [Iconv.conv("gbk","utf-8",'楼宇名称'),Iconv.conv("gbk","utf-8",'地址'),Iconv.conv("gbk","utf-8",'社区规模'),Iconv.conv("gbk","utf-8",'入住率'),Iconv.conv("gbk","utf-8",'联系人'),Iconv.conv("gbk","utf-8",'媒体总位')], format)
    @pubs=Publisher.find(:all)
    i=2
    for pub in @pubs
    # name=District.find_by_id(pub.district_id).name
    worksheet.write(i, 0,[Iconv.conv("gbk","utf-8",pub.name),Iconv.conv("gbk","utf-8",pub.location),pub.customer_sum,pub.occupancy_rate,Iconv.conv("gbk","utf-8",pub.contact),pub.total_num])
      i+=1
    end
  workbook.close
  end

你可能感兴趣的:(mysql,wordpress,Excel,ActiveRecord,Rails)