ruby on rails 中使用CSV匯出excel檔案
阿新 • • 發佈:2019-01-29
Exporting CSV and Excel
config/application.rb
require 'csv'
index.html.erb
<p>
Download:
<%= link_to 'CSV', products_path(format: "csv") %>
<%= Link_to 'Excel', products_path(format: "xls") %>
</p>
products_controller.rb
def index
@products = Product .all #可以使用select等進行篩選
respond_to do |format|
format.html
format.csv { send_data @products.to_csv }
format.csv { send_data @products.to_xls }
end
end
modle/product.rb
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names #column_names是由資料庫表的所有列名組成的陣列,可自定義陣列代替,以便查詢匯出資料
all.each do |product|
csv << product.attributes.values_at(*column_names)
end
end
end
config/initializers/mime_type.rb
Mime::Type.register "application/xls", xls
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>