可以使用Report寶石,它生成的PDF,但也XLSX和CSV。
# a fake Manufacturer class - you probably have an ActiveRecord model
Manufacturer = Struct.new(:name, :gsa)
require 'report'
class ManufacturerReport < Report
table 'Manufacturers' do # you can have multiple tables, which translate into multiple sheets in XLSX
head do
row 'Manufacturer report'
end
body do
rows :manufacturers
column 'Name', :name
column 'GSA?', :gsa
end
end
# you would want this so that you can pass in an array
# attr_reader :manufacturers
# def initialize(manufacturers)
# @manufacturers = manufacturers
# end
def manufacturers
[
Manufacturer.new('Ford', true),
Manufacturer.new('Fischer', false),
Manufacturer.new('Tesla', nil),
]
end
end
當你調用report.pdf.path
,一個PDF的產生在tmp目錄:
@manufacturers = Manufacturer.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @manufacturers }
format.pdf do
report = ManufacturerReport.new(@manufacturers) # using the commented-out code
send_file report.pdf.path, :type => 'application/pdf', :disposition => 'attachment', :filename => 'ManufacturersReport.pdf'
# tmp files are periodically cleaned up by the operating system, but if you want to be extra clean you can call
# report.cleanup
# but this may remove the tmp files before apache/nginx/etc. finishes delivering the file
end
end
最終結果:
report = ManufacturerReport.new
puts report.pdf.path #=> /tmp/185051406_Report__Pdf.pdf
puts report.xlsx.path #=> /tmp/185050541_Report__Xlsx.xlsx
你可以在你的控制器喜歡做
PDF
XLSX
注意,XLSX具有自動篩選會自動爲你添加。
也Theres上PDFKit一個railscast - http://railscasts.com/episodes/220-pdfkit – alternative 2010-11-07 13:25:40
wicked_pdf是怎麼我現在正在做這些,請參閱@Thilo的答案 – wesgarrison 2011-07-21 15:19:22