0

I'm using the (Axlsx gem and it's working great, but I need to add an image to a cell. I know it can be done with an image file (see Adding image to Excel file generated by Axlsx.?), but I'm having a lot of trouble using our images stored in S3 (through Carrierwave).

Things I've tried:

# image.url = 'http://.../test.jpg'
ws.add_image(:image_src => image.url,:noSelect => true, :noMove => true) do |image|

# ArgumentError: File does not exist

or

ws.add_image(:image_src => image,:noSelect => true, :noMove => true) do |image|
# Invalid Data #<Object ...> 

Not sure how to proceed

Community
  • 1
  • 1
AlexQueue
  • 6,353
  • 5
  • 35
  • 44

2 Answers2

2

Try using read to pull the contents into a tempfile and use that location:

t = Tempfile.new('my_image')
t.binmode
t.write image.read
t.close
ws.add_image(:image_src => t.path, ...
PinnyM
  • 35,165
  • 3
  • 73
  • 81
  • `ArgumentError: File does not exist`. I think it's looking for that as though it's an absolute path when it's just the path in the URL. – AlexQueue Feb 03 '14 at 21:15
  • Hmm, can you `read` it into a tempfile and use that location? Updated to demonstrate... – PinnyM Feb 03 '14 at 21:45
  • Used something similar. `t.write open(image.url).read`, but BEWARE because this only works on images over 10kb (http://stackoverflow.com/questions/10496874/why-does-openuri-treat-files-under-10kb-in-size-as-stringio) – AlexQueue Feb 10 '14 at 21:50
0

To add an alternative answer for Paperclip & S3 as I couldn't find a reference for that besides this answer.

I'm using Rails 5.0.2 and Paperclip 4.3.1.

With image URLs like: http://s3.amazonaws.com/prod/accounts/logos/000/000/001/original/logo.jpg?87879987987987

@logo = @account.company_logo
if @logo.present?
  @logo_image = Tempfile.new(['', ".#{@logo.url.split('.').last.split('?').first}"])
  @logo_image.binmode # note that our tempfile must be in binary mode
  @logo_image.write open(@logo.url).read
  @logo_image.rewind
end

In the .xlsx file

sheet.add_image(image_src:  @logo_image.path, noSelect: true, noMove: true, hyperlink: "#") do |image|... 

Reference link: http://mensfeld.pl/tag/tempfile/ for more reading.

The .split('.').last.split('?').first is to get .jpg from logo.jpg? 87879987987987.

rylanb
  • 604
  • 6
  • 15