开发者

generating excel in rails

开发者 https://www.devze.com 2023-01-24 07:01 出处:网络
I am trying to create an excel sheet in ruby on rails. So I used the plugin Rexcel. When I am runni开发者_运维百科ng the application I am getting the following error.

I am trying to create an excel sheet in ruby on rails. So I used the plugin Rexcel. When I am runni开发者_运维百科ng the application I am getting the following error.

uninitialized constant Rexcel::Workbook::Builder

I had added the following code, then this error hitting

workbook = Rexcel::Workbook.new

worksheet = workbook.add_worksheet("Customers")

worksheet.add_line("name","test")

headers['Content-Type'] = "application/vnd.ms-excel"

headers['Content-Disposition'] = 'attachment; filename="excel-export.xlsx"'
headers['Cache-Control'] = 'max-age=0'
headers['pragma']="public"
workbook.build

How to solve this?


I would advice to use Spreadsheet instead of Rexcel because is definitely more mature and I'm using it with Rails 3 with no problems.

Here is the documentation.

The overall process would be:

book = Spreadsheet::Workbook.new
sheet = book.create_worksheet :name => 'Customers'
sheet.row(0).concat %w{Name Country Acknowlegement}
book.write '/path/to/output/excel-file.xls'


+1 to tommasop

I'd like to add. If you, like me, you consider this as presenting data, just like xml, html or json, you don't want to write to disc. Heroku is read-only if you're considering using that.

I would change the book.write '/somepath..' to

def xls
  .. your stuff .. 
  blob = StringIO.new("")
  book.write blob
  blob.string
end

then, in the controller do

send_data @customer.xls, :type => :xls, :filename => @customer.xls_file_name

remember to add the mime type in your initializer NOTE, I just realized that these examples are from my rails 2.3.10 app. Maybe it differs in rails 3.

Mime::Type.register "application/vnd.ms-excel", :xls
0

精彩评论

暂无评论...
验证码 换一张
取 消