[ruby on rails] excel导入与导出

本文介绍了如何在Ruby on Rails应用中使用spreadsheet gem进行Excel文件的导入和导出。首先,在配置文件中添加mime类型支持,然后分别在控制器和模型中实现导出和导入功能。导出部分涉及在控制器和模型中的操作,以及在视图中的调用。导入部分讲解了在视图中创建导入表单,并在控制器中处理上传。
使用spreadsheet(只支持xls)

spreadsheet gem

gem 'spreadsheet'
  • 首先在 config/initializers/mime_types.rb 中添加
Mime::Type.register "text/excel", :xls  
1.导出
  • controller中添加
def index
  @systems = System.all
  respond_to do |format|
      format.html
      format.xls {send_data(System.exprot_to_xls(@systems),
                            :type => "text/excel;charset=utf-8; header=present",
                            :filename => "系统资产-#{Time.now.to_date}.xls")
      }
  end
end
  • model中添加
def self.exprot_to_xls(systems)
    xls_report = StringIO.new
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet::Workbook.new
    style0 = Spreadsheet::Format.new :weight => :bold, :size => 12, :align => :center, :text_wrap => 1, :vertical_align => :center
    style = Spreadsheet::Format.new :size => 11, :text_wrap => 1, :vertical_align => :center
    sheet1 = book.create_worksheet :name => "系统资产统计表.xls"
    # 设置单元格高度
    sheet1.row(0).height = 30
    sheet1.row(0).default_format = style0
    # 设置单元格宽度
     sheet1.column(1).width = 15
     sheet1.column(2).width = 15
    sheet1.row(0).concat ["序号", "单位名称", "信息系统名称"]

    systems.each_with_index do |system, index|
      sheet1.column(index+1).width = 18
      sheet1.row(index+1).default_format = style
      sheet1.row(index+1).height = 30
      sheet1.row(index+1)[0] = index + 1
      sheet1.row(index+1)[1] = system.name
      sheet1.row(index+1)[2] = system.system_name
    end

    book.write xls_report
    xls_report.string
  end
  • view中调用
<%= form_tag systems_path(format: :xls), method: :get do %>
<%= submit_tag '导出', class: 'btn btn-xs btn-primary' %>

#or
<%= link_to '导出', systems_path(format: :xls), class: 'btn btn-xs btn-primary' %>
2.导入
  • view中创建导入form
<%= form_tag import_systems_path, multipart: true do %>
  <%= file_field_tag :file, style: 'display: inline; width: 200px;' %>
  <%= submit_tag '导入', class: 'btn btn-xs btn-primary' %>
<% end %>
  • controller中使用
def import
    systems_sheet = Spreadsheet.open(params[:file].path).worksheet(0)
    systems_sheet.each_with_index do |row, index|
      if index > 1
        value_hash = {}
        value_hash[:name] = row[2]&.strip
        value_hash[:data_type] = row[3]&.strip
        value_hash[:data_size] = row[4]&.strip
        existed_system = System.find_by(name: row[2])&.strip
        if existed_system.present?
          existed_system.update(value_hash)
        else
          System.create(value_hash)
        end
      end
    end
    redirect_to systems_path
  end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值