rails匯出csv亂碼問題
阿新 • • 發佈:2019-01-24
使用wicegird匯出csv檔案,參照wicegird的官方例子,比較順利,但是在測試發現window下,excel開啟不會自動轉換(只能通過新建excel,開啟以後匯入才有正確的格式),修改csv的分割符號,只有逗號excel開啟的時候才會自動轉換.
Controller:
def bill @issue_numbers_grid = initialize_grid(IssueNumber, include: :number, per_page:20, order:'issue_numbers.id', order_direction: 'desc', enable_export_to_csv: true, # csv_field_separator: ';',#預設使用,號 csv_file_name:"賬單" ) export_grid_if_requested('grid' => 'issue_numbers_grid') do # usual render or redirect code executed if the request is not a CSV export request end end
rails匯出的csv文件預設是使用utf-8,但是一般window下excel開啟的時就出現亂碼了.在到處csv的頭行最開始加入"\xEF\xBB\xBF"(ruby檔案中必須要用雙引號,真正生成的時候編譯成csv的BOM頭),window下excel開啟時竟然自動進行了編碼轉換.
bill.html.erb
<p> <button data-grid-name="grid" class="btn btn-primary wg-external-csv-export-button">匯出</button> </p> <%= render 'issue_numbers_grid' %> <%= link_to t('.back', :default => t("helpers.links.back")), customers_path, :class => 'btn btn-default' %>
_issue_numbers_grid.html.erb
<%= grid(@issue_numbers_grid, hide_csv_button:true) do |g| g.blank_slate content_tag(:div, "無記錄", class: 'well') g.column name:"\xEF\xBB\xBF號碼", attribute: 'phone_num' g.column name:"語音通訊費" ,attribute: 'voice' g.column name:"簡訊彩信費" ,attribute: 'message' end -%>