Web设计的Ruby on Rails
第7章 通过CSV格式加载Excel数据

这一章中,对使用 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 ,确认显示的是下面内容。
| 姓名 | 邮箱地址 | 年龄 |
|---|---|---|
| taro | taro@sample.com | 39 |
| jiro | jiro@sample.com | 35 |
| saburo | saburo@sample.com | 31 |
读者中肯定也有人担心文字代码的处理的吧。
用 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 。数组 row 的 collect 方法,将数组要素一个个地存储进变量 value ,执行代码块(大括号括住的代码),从结果中生成新的数组。
刷新浏览器,这下没问题了。
| 姓名 | 邮箱地址 | 年龄 |
|---|---|---|
| 太郎 | taro@sample.com | 39 |
| jiro | jiro@sample.com | 35 |
| saburo | saburo@sample.com | 31 |
(2008/02/23)
- 前言
- 第1章 使用 Ruby on Rails 进行Web制作时的基本流程 (2007/09/24)
- 第2章 变量、数组、散列表 (2007/10/01)
- 第3章 布局和局部模板 (2007/10/08)
- 第4回 Rails的安装和Web服务器的启动 (2007/10/22)
- 第5章 模板文件的配置与命名规则 (2007/11/12)
- 第6回 YAML文件处理 (2007/12/03)
- 第7章 通过CSV格式加载Excel数据 (2008/02/23)

