Skip to content

Instantly share code, notes, and snippets.

@randym
Created October 30, 2012 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randym/3980434 to your computer and use it in GitHub Desktop.
Save randym/3980434 to your computer and use it in GitHub Desktop.
Surrounding Box Border in Axlsx
require 'axlsx'
p = Axlsx::Package.new
p.workbook do |wb|
# Stuff like this is why I LOVE RUBY
# If you dont know about hash default values
# LEARN IT! LIVE IT! LOVE IT!
defaults = { :style => :thick, :color => "000000" }
borders = Hash.new do |hash, key|
hash[key] = wb.styles.add_style :border => defaults.merge( { :edges => key.to_s.split('_').map(&:to_sym) } )
end
top_row = [0, borders[:top_left], borders[:top], borders[:top], borders[:top_right]]
middle_row = [0, borders[:left], nil, nil, borders[:right]]
bottom_row = [0, borders[:bottom_left], borders[:bottom], borders[:bottom], borders[:bottom_right]]
wb.add_worksheet(:name => "Boxed Border") do |ws|
ws.add_row []
ws.add_row ['', 1,2,3,4], :style => top_row
ws.add_row ['', 5,6,7,8], :style => middle_row
ws.add_row ['', 9, 10, 11, 12]
#This works too!
ws.rows.last.style = bottom_row
end
end
p.serialize 'boxed_border.xlsx'
@randym
Copy link
Author

randym commented Dec 19, 2012

For this use case, I would define the following styles:

top_left, top, top_right, right, bottom_right, bottom, bottom_left, left

and apply them as I needed. I know this is a PITA!
Style in Office Open XML is really way too much work.
It is very sad that they could not learn from CSS when they designed the spec.

Inheriting styles would simply this so much.....

If you are looking to add some functionality to the library, there are a couple of things you are going to want to be sure to understand.

  1. Style is an integer value defined on each cell.
  2. That integer value looks up one (and only one) xf record from Style#xfs
  3. Incremental styles are possible with dxf records

There is a pretty steep learning curve here, so in addition to understanding the spec, I find it helpful to unzip a saved file from excel that gives me the results I want, and analyze that to see how MS solved the problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment