Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge Cells #51

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions lib/xlsxtream/worksheet.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def initialize(io, options = {})
@rownum = 1
@closed = false
@options = options
@xml_merge_cells = nil

write_header
end
Expand All @@ -18,6 +19,18 @@ def <<(row)
@rownum += 1
end
alias_method :add_row, :<<

# refs: ['A1:B1', 'C1:G1', 'A2:G2', ...]
def merge_cells(refs)
xml = String.new(%Q{<mergeCells r="#{refs.length}">})

refs.each do |ref|
xml << %Q{<mergeCell ref="#{ref}"/>}
end

xml << '</mergeCells>'
@xml_merge_cells = xml
end

def close
write_footer
Expand Down Expand Up @@ -57,6 +70,7 @@ def write_header
def write_footer
@io << XML.strip(<<-XML)
</sheetData>
#{@xml_merge_cells}
</worksheet>
XML
end
Expand Down
22 changes: 22 additions & 0 deletions test/xlsxtream/worksheet_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,5 +101,27 @@ def test_respond_to_name
ws = Worksheet.new(StringIO.new, name: 'test')
assert_equal 'test', ws.name
end

def test_with_merge_cells
io = StringIO.new
ws = Worksheet.new(io)
ws << ['foo']
ws.add_row ['bar']
ws.add_row ['foobar']
ws.merge_cells(['A1:B1', 'A3:B3'])
ws.close
expected = \
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'"\r\n" \
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>' \
'<row r="1"><c r="A1" t="inlineStr"><is><t>foo</t></is></c></row>' \
'<row r="2"><c r="A2" t="inlineStr"><is><t>bar</t></is></c></row>' \
'<row r="3"><c r="A3" t="inlineStr"><is><t>foobar</t></is></c></row>' \
'</sheetData>' \
'<mergeCells r="2">' \
'<mergeCell ref="A1:B1"/>' \
'<mergeCell ref="A3:B3"/>' \
'</mergeCells></worksheet>'
assert_equal expected, io.string
end
end
end