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

Use worksheet without block #45

Merged
merged 8 commits into from
Jun 27, 2020
Merged
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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ xlsx.write_worksheet(name: 'SheetWithAutoFormat', auto_format: true) do |sheet|
sheet << ['true', '11.85', '2050-01-01T12:00', '1984-01-01']
end

# You can also create worksheet without a block, using the `add_worksheet` method.
# It can be only used sequentially, so remember to manually close the worksheet
# when you are done (before opening a new one).
worksheet = xls.add_worksheet(name: 'SheetWithoutBlock')
worksheet << ['some', 'data']
worksheet.close

# Writes metadata and ZIP archive central directory
xlsx.close
# Close IO object
Expand Down
63 changes: 43 additions & 20 deletions lib/xlsxtream/workbook.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,30 +55,32 @@ def initialize(output, options = {})
@io = IO::ZipTricks.new(output)
end
@sst = SharedStringTable.new
@worksheets = Hash.new { |hash, name| hash[name] = hash.size + 1 }
@worksheets = []
end

def write_worksheet(name = nil, options = {})
if name.is_a? Hash and options.empty?
options = name
name = nil
def add_worksheet(*args, &block)
if block_given?
# This method used to be an alias for `write_worksheet`. This was never publicly documented,
# but to avoid breaking this private API we keep the old behaviour when called with a block.
Kernel.warn "#{caller.first[/.*:\d+:(?=in `)/]} warning: Calling #{self.class}#add_worksheet with a block is deprecated, use #write_worksheet instead."
felixbuenemann marked this conversation as resolved.
Show resolved Hide resolved
return write_worksheet(*args, &block)
end
felixbuenemann marked this conversation as resolved.
Show resolved Hide resolved
use_sst = options.fetch(:use_shared_strings, @options[:use_shared_strings])
auto_format = options.fetch(:auto_format, @options[:auto_format])
columns = options.fetch(:columns, @options[:columns])
sst = use_sst ? @sst : nil

name = name || options[:name] || "Sheet#{@worksheets.size + 1}"
sheet_id = @worksheets[name]
@io.add_file "xl/worksheets/sheet#{sheet_id}.xml"
unless @worksheets.all? { |ws| ws.closed? }
fail Error, "Close the current worksheet before adding a new one"
end

build_worksheet(*args)
end

def write_worksheet(*args)
worksheet = build_worksheet(*args)

worksheet = Worksheet.new(@io, :sst => sst, :auto_format => auto_format, :columns => columns)
yield worksheet if block_given?
worksheet.close

nil
end
alias_method :add_worksheet, :write_worksheet

def close
write_workbook
Expand All @@ -93,6 +95,27 @@ def close
end

private
def build_worksheet(name = nil, options = {})
if name.is_a? Hash and options.empty?
options = name
name = nil
end

use_sst = options.fetch(:use_shared_strings, @options[:use_shared_strings])
auto_format = options.fetch(:auto_format, @options[:auto_format])
columns = options.fetch(:columns, @options[:columns])
sst = use_sst ? @sst : nil

sheet_id = @worksheets.size + 1
name = name || options[:name] || "Sheet#{sheet_id}"

@io.add_file "xl/worksheets/sheet#{sheet_id}.xml"

worksheet = Worksheet.new(@io, :id => sheet_id, :name => name, :sst => sst, :auto_format => auto_format, :columns => columns)
@worksheets << worksheet

worksheet
end

def write_root_rels
@io.add_file "_rels/.rels"
Expand All @@ -113,8 +136,8 @@ def write_workbook
<workbookPr date1904="false"/>
<sheets>
XML
@worksheets.each do |name, sheet_id|
@io << %'<sheet name="#{XML.escape_attr name}" sheetId="#{sheet_id}" r:id="#{rid.next!}"/>'
@worksheets.each do |worksheet|
@io << %'<sheet name="#{XML.escape_attr worksheet.name}" sheetId="#{worksheet.id}" r:id="#{rid.next!}"/>'
end
@io << XML.strip(<<-XML)
</sheets>
Expand Down Expand Up @@ -189,8 +212,8 @@ def write_workbook_rels
@io.add_file "xl/_rels/workbook.xml.rels"
@io << XML.header
@io << '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
@worksheets.each do |name, sheet_id|
@io << %'<Relationship Id="#{rid.next!}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet#{sheet_id}.xml"/>'
@worksheets.each do |worksheet|
@io << %'<Relationship Id="#{rid.next!}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet#{worksheet.id}.xml"/>'
end
@io << %'<Relationship Id="#{rid.next!}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>'
@io << %'<Relationship Id="#{rid.next!}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>' unless @sst.empty?
Expand All @@ -208,8 +231,8 @@ def write_content_types
<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
XML
@io << '<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>' unless @sst.empty?
@worksheets.each_value do |sheet_id|
@io << %'<Override PartName="/xl/worksheets/sheet#{sheet_id}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
@worksheets.each do |worksheet|
@io << %'<Override PartName="/xl/worksheets/sheet#{worksheet.id}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
end
@io << '</Types>'
end
Expand Down
14 changes: 14 additions & 0 deletions lib/xlsxtream/worksheet.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class Worksheet
def initialize(io, options = {})
felixbuenemann marked this conversation as resolved.
Show resolved Hide resolved
@io = io
@rownum = 1
@closed = false
@options = options

write_header
Expand All @@ -20,6 +21,19 @@ def <<(row)

def close
write_footer
@closed = true
end

def closed?
@closed
end

def id
@options[:id]
end

def name
@options[:name]
end

private
Expand Down
102 changes: 98 additions & 4 deletions test/xlsxtream/workbook_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def test_empty_workbook
def test_workbook_with_sheet
iow_spy = io_wrapper_spy
Workbook.open(iow_spy) do |wb|
wb.add_worksheet
wb.write_worksheet
end
expected = {
'xl/worksheets/sheet1.xml' =>
Expand Down Expand Up @@ -80,10 +80,80 @@ def test_workbook_with_sheet
end
end

def test_deprecated_add_workbook_with_block
iow_spy = io_wrapper_spy
Workbook.open(iow_spy) do |wb|
silence_warnings do
wb.add_worksheet {}
end
end
expected = {
'xl/worksheets/sheet1.xml' =>
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'"\r\n" \
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' \
'<sheetData></sheetData>' \
'</worksheet>',
'xl/workbook.xml' =>
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'"\r\n" \
'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '\
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' \
'<workbookPr date1904="false"/>' \
'<sheets>' \
'<sheet name="Sheet1" sheetId="1" r:id="rId1"/>' \
'</sheets>' \
'</workbook>',
'xl/_rels/workbook.xml.rels' =>
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'"\r\n" \
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' \
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>' \
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>' \
'</Relationships>'
}
actual = iow_spy
expected.keys.each do |path|
assert_equal expected[path], actual[path]
end
end

def test_workbook_with_sheet_without_block
iow_spy = io_wrapper_spy
Workbook.open(iow_spy) do |wb|
ws = wb.add_worksheet
ws << ['foo']
ws.close
end
expected = {
'xl/worksheets/sheet1.xml' =>
'<?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></sheetData>' \
'</worksheet>',
'xl/workbook.xml' =>
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'"\r\n" \
'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '\
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' \
'<workbookPr date1904="false"/>' \
'<sheets>' \
'<sheet name="Sheet1" sheetId="1" r:id="rId1"/>' \
'</sheets>' \
'</workbook>',
'xl/_rels/workbook.xml.rels' =>
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'"\r\n" \
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' \
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>' \
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>' \
'</Relationships>'
}
actual = iow_spy
expected.keys.each do |path|
assert_equal expected[path], actual[path]
end
end

def test_workbook_with_sst
iow_spy = io_wrapper_spy
Workbook.open(iow_spy) do |wb|
wb.add_worksheet(nil, use_shared_strings: true) do |ws|
wb.write_worksheet(nil, use_shared_strings: true) do |ws|
ws << ['foo']
end
end
Expand Down Expand Up @@ -188,6 +258,23 @@ def test_write_multiple_worksheets
end
end

def test_must_write_sequentially
iow_spy1 = io_wrapper_spy

Workbook.open(iow_spy1) do |wb|
wb.add_worksheet.tap { |ws| ws.close }
wb.add_worksheet.tap { |ws| ws.close }
end

iow_spy2 = io_wrapper_spy
assert_raises(Xlsxtream::Error) do
Workbook.open(iow_spy2) do |wb|
wb.add_worksheet
wb.add_worksheet # adding a second worksheet without closing
end
end
end

def test_write_named_worksheet
iow_spy = io_wrapper_spy
Workbook.open(iow_spy) do |wb|
Expand Down Expand Up @@ -239,7 +326,7 @@ def test_worksheet_name_as_option
def test_add_columns_via_workbook_options
iow_spy = io_wrapper_spy
Workbook.open(iow_spy, { :columns => [ {}, {}, { :width_pixels => 42 } ] } ) do |wb|
wb.add_worksheet {}
wb.write_worksheet {}
end

expected = \
Expand All @@ -258,7 +345,7 @@ def test_add_columns_via_workbook_options
def test_add_columns_via_workbook_options_and_add_rows
iow_spy = io_wrapper_spy
Workbook.open(iow_spy, { :columns => [ {}, {}, { :width_pixels => 42 } ] } ) do |wb|
wb.add_worksheet do |ws|
wb.write_worksheet do |ws|
ws << ['foo']
ws.add_row ['bar']
end
Expand Down Expand Up @@ -397,5 +484,12 @@ def io_wrapper_spy
IO::Hash.new(StringIO.new)
end

def silence_warnings
old_verbose, $VERBOSE = $VERBOSE, nil
yield
ensure
$VERBOSE = old_verbose
end

end
end
10 changes: 10 additions & 0 deletions test/xlsxtream/worksheet_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,5 +91,15 @@ def test_add_columns_via_worksheet_options_and_add_rows
'</sheetData></worksheet>'
assert_equal expected, io.string
end

def test_respond_to_id
ws = Worksheet.new(StringIO.new, id: 1)
assert_equal 1, ws.id
end

def test_respond_to_name
ws = Worksheet.new(StringIO.new, name: 'test')
assert_equal 'test', ws.name
end
end
end