rails csv excel 导入导出

<p>
  Download:
  <%= link_to "CSV", products_path(format: "csv") %> |
  <%= link_to "Excel", products_path(format: "xls") %>
</p>
参考:

http://railscasts.com/episodes/362-exporting-csv-and-excel?autoplay=true

http://railscasts.com/episodes/396-importing-csv-and-excel?autoplay=true


csv 是ruby的标准库:

http://ruby-doc.org/stdlib-1.8.7/libdoc/csv/rdoc/CSV.html

使用前先require

config/application.rb


require 'csv'

在controller中加入格式支持:

products_controller.rb


def index @products = Product.order(:name)
  respond_to do |format|
    format.html
    format.csv { send_data @products.to_csv }
    format.xls # { send_data @products.to_csv(col_sep: "\t") } end end

send_data会让文件下载,用render会打在页面上

使用http://localhost:3000/products.csv  试一下

上面没有完成to_csv方法要定义下

models/product.rb


def self.to_csv(options = {}) CSV.generate(options) do |csv|
    csv << column_names
    all.each do |product|
      csv << product.attributes.values_at(*column_names) end end end


column_names是所有的表里的字段,可以在这个基础上加减

excel可以用

send_data @products.to_csv(col_sep: "\t")



达到同csv一样的效果.

还可以考虑使用xml.erb进行复杂的渲染操作

views/products/index.xls.erb


<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:html="http://www.w3.org/TR/REC-html40">
  <Worksheet ss:Name="Sheet1">
    <Table>
      <Row>
        <Cell><Data ss:Type="String">ID</Data></Cell>
        <Cell><Data ss:Type="String">Name</Data></Cell>
        <Cell><Data ss:Type="String">Release Date</Data></Cell>
        <Cell><Data ss:Type="String">Price</Data></Cell>
      </Row>
    <% @products.each do |product| %>
      <Row>
        <Cell><Data ss:Type="Number"><%= product.id %></Data></Cell>
        <Cell><Data ss:Type="String"><%= product.name %></Data></Cell>
        <Cell><Data ss:Type="String"><%= product.released_on %></Data></Cell>
        <Cell><Data ss:Type="Number"><%= product.price %></Data></Cell>
      </Row>
    <% end %>
    </Table>
  </Worksheet>
</Workbook>


完成这个还需要加入相应的mime_types

config/initializers/mime_types.rb


Mime::Type.register "application/xls", :xls


下载接连;

<p>
  Download:
  <%= link_to "CSV", products_path(format: "csv") %> |
  <%= link_to "Excel", products_path(format: "xls") %>
</p>

导入:








你可能感兴趣的:(rails csv excel 导入导出)