export to public folder using axlsx
Asked Answered
B

2

11

I am using the axlsx gem to create excel files. I get them serialized in my project home directory as an xlsx file. But I want the file to be created in the public folder of my rails app, or directly downloadable by the user without saving it in the server. How can I do this?? Here is the controller that generates the xlsx file

def export_excel
    p = Axlsx::Package.new
    wb = p.workbook 
    wb.add_worksheet(:name => "Basic Worksheet") do |sheet|
    (1..10).each { |label| sheet.add_row [label, rand(24)+1] }
    sheet.add_chart(Axlsx::Bar3DChart, :start_at => "A14", :end_at => "F24") do |chart|
        chart.add_series :data => sheet["B1:B10"], :labels => sheet["A1:A10"], :title => sheet["A1"]
    end
  end
  p.serialize('charts.xlsx')    

end
Baldridge answered 14/3, 2013 at 6:14 Comment(1)
Its so simple. Just say p.serialize('public/charts.xlsx')Baldridge
B
4
p = Axlsx::Package.new
# ...
outstrio = StringIO.new
p.use_shared_strings = true # Otherwise strings don't display in iWork Numbers
outstrio.write(p.to_stream.read)
outstrio.string

This will yield the file contents of the xls file. Then you can either send_data it to the user, or save it to a file on disk.

Bregma answered 14/3, 2013 at 6:20 Comment(2)
this is what i did: 'outstrio = StringIO.new p.use_shared_strings = true outstrio.write(p.to_stream.read) send_data outstrio.string, :filename=>"report.xlsx"''Baldridge
fearpi is correct. Thanks! In addition to @Baldridge to write a file in a disk. file = File.open("#{Rails.root}/tmp/temp.csv", 'w') file.write outstrio.stringMirisola
M
0

Late answer: You could also use the axlsx_rails gem. It adds a template handler for axlsx, making it very easy to generate and serve xlsx files:

https://github.com/straydogstudio/axlsx_rails

It lets you put all your axlsx code in views, with partials. If you are doing lots of xlsx in rails, it is handy.

Of course, serialize works fine too, or to stream as @fearpi mentioned.

Mcginn answered 27/7, 2013 at 3:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.