`
jsntghf
  • 浏览: 2482538 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

把数据导入excel

阅读更多

首先下个插件excel,在项目根目录执行

ruby script/plugin install http://svn.napcsweb.com/public/excel


此时就会在项目的vendor目录下多个文件夹。里面有个excel.rb,这就是我们要用的核心方法。
然后转到model

class User < ActiveRecord::Base USERTYPE = [["普通学员", 0], ["讲师", 1], ["系统管理员", 2]] end


接下来,再看看控制器的实现

class UserController < ApplicationController include ActiveSupport def export users = User.all array = Array.new for i in 0...users.length item = OrderedHash.new item["姓名"] = users[i].name item["用户类型"] = User::USERTYPE.rassoc(users[i].usertype.to_i)[0] item["加入时间"] = users[i].created_at.to_s(:db) array << item end e = Excel::Workbook.new e.addWorksheetFromArrayOfHashes("Users", array) headers['Content-Type'] = "application/vnd.ms-excel" render :text => e.build end end


现在就ok了,但是注意OrderedHash,这个hash是有序的,别慌,需要在控制器里面加入include ActiveSupport,这样OrderedHash才可以用。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics