gem – PullMonkey Blog http://pullmonkey.com Thu, 26 Apr 2012 19:17:20 +0000 en-US hourly 1 https://wordpress.org/?v=5.6 Headers and Footers in ruby’s Spreadsheet gem http://pullmonkey.com/2012/04/26/headers-and-footers-in-rubys-spreadsheet-gem/ http://pullmonkey.com/2012/04/26/headers-and-footers-in-rubys-spreadsheet-gem/#comments Thu, 26 Apr 2012 19:17:20 +0000 http://pullmonkey.com/?p=57696 Have you ever needed to add a header or footer to your spreadsheets in ruby?
Yah, well, we have 🙁
Yes, you can do this with the Write Excel gem.
But we've already written years worth of spreadsheet code with the spreadsheet gem and don't want to rewrite it all.

Anyway, we thought we'd share our little trick to get page headers using the spreadsheet gem.

So what you see here (above) goes into a config/initializer, something like RAILS_ROOT/config/initializer/enable_headers_in_spreadsheet_gem.rb. Here's what's going on:

1) We know that the write_from_scratch method is called when everything is said and done and the data is ready to be written to the spreadsheet file. So we make use of this and alias that method to write_from_scratch_without_header. Which opens us up to call our write_header method inside our write_from_scratch method which, of course, will call the original write_from_scratch method.

2) Our write_header method makes use of the already existing opcode for Header in the spreadsheet gem. It's not being used, so my guess is the developers intend on solving this issue at some point. We have to send the opcode, the length info and the string we want to write out. This was the trickiest part to figure out.

3) We expose an add_header method that simply takes a string and stores it in the header accessor. This means, to set the header, you simply say sheet.add_header("foo header").

To implement the footer, you'd just do the same thing, create a footer accessor, add a method to update it. Then build the writer_footer method with opcode(:footer) and append write_footer at the end of write_from_scratch.

Well, that took us some time to figure out, so enjoy and let me know if you have any questions.

]]>
http://pullmonkey.com/2012/04/26/headers-and-footers-in-rubys-spreadsheet-gem/feed/ 1