icon Web设计的Ruby on Rails

第7章 通过CSV格式加载Excel数据

designer_image_002

这一章中,对使用 Ruby on Rails 利用逗号分隔(CSV)格式的数据的方法进行说明。

首先,请准备好上图中的 Excel 文件 table2.xls

Excel“保存”菜单中,“文件类型”选择CSV(逗号分隔),保存为 RAILS_ROOT/data/table2.csv 。如果 RAILS_ROOT/data 目录不存在,就请创建一个。

使用这个数据表示表 TablesController 如下。

require 'csv'
class TablesController < ActionController
  def show
    id = params[:id]
    @records = []
    reader = CSV.open(RAILS_ROOT + "/data/table#{id}.csv", 'r')
    reader.shift
    reader.each {|row| @records << row }
  end
end

注意一下和上一章中生成的表 TablesController 的区别。

要点如下:

  • 开头写入 require 'csv' 以加载CSV 模块。
  • CSV.open 的第二参数中,指定表示载入模式的字符串 'r'
  • 使用 shift 方法跳过 CSV 数据的开头行
  • @records << row 的写法,在 @records 末尾加上 row 元素。

模板 show.rhtml 也和前一章有些许不同。

<table border="1" cellpadding="4">
  <tr>
    <th>姓名</th>
    <th>邮箱地址</th>
    <th>年龄</th>
  </tr>
<% @records.each do |record| -%>
  <tr>
    <td><%= record[0] %></td>
    <td><%= record[1] %></td>
    <td><%= record[2] %></td>
  </tr>
<% end -%>
</table>

前一章中变量 record 是散列表,在这章中却是数组。不能写成 record['email'] 的形式。

在浏览器上搜索 http://localhost:3000/tables/show/2 ,确认显示的是下面内容。

姓名邮箱地址年龄
tarotaro@sample.com39
jirojiro@sample.com35
saburosaburo@sample.com31

读者中肯定也有人担心文字代码的处理的吧。

用 Excel 打开RAILS_ROOT/data/table2.csv ,试着把“taro”变为“太郎”,刷新浏览器……,失败了,变成了乱码。

Excel 做的 CSV 文件的文字编码是 Shift JIS ,而 Rails 的文字编码是 UTF-8,所以需要做一下转换。

require 'csv'
class TablesController < ActionController
  def show
    id = params[:id]
    @records = []
    reader = CSV.open(RAILS_ROOT + "/data/table#{id}.csv", 'r')
    reader.shift
    reader.each do |row|
      row = row.collect {|value| NKF.nkf('-Sw', value) }
      @records << row
    end
  end
end

NKF 模块的方法 nkf 改变日语字符串的文字编码。第1参数 '-Sw' ,表示输入时是 Shift JIS,输出时显示为 UTF-8 。数组 rowcollect 方法,将数组要素一个个地存储进变量 value ,执行代码块(大括号括住的代码),从结果中生成新的数组。

刷新浏览器,这下没问题了。

姓名邮箱地址年龄
太郎taro@sample.com39
jirojiro@sample.com35
saburosaburo@sample.com31

(2008/02/23)