rbxl 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,12 +19,28 @@ module Rbxl
19
19
  # memory scales with that sheet's on-disk size. Use the write-only mode
20
20
  # (+Rbxl.new+) for that case instead.
21
21
  #
22
- # == Out of scope (1.4.0)
22
+ # == Styles
23
23
  #
24
- # * inserting / deleting / reordering / duplicating sheets
25
- # * editing styles, formulas, named ranges, drawings, or shared strings
26
- # * +Date+ / +Time+ / +DateTime+ values (raise {EditableCellTypeError};
27
- # convert to a numeric serial yourself if you need a date cell)
24
+ # {EditableCell#style} tweaks a cell's existing (template) style and
25
+ # {#add_style} registers a new one. Both only <em>append</em> entries to
26
+ # +xl/styles.xml+, so the style indices existing cells use never change;
27
+ # the part is rewritten only when a style was actually added.
28
+ #
29
+ # == Recalculation
30
+ #
31
+ # Cached formula results in a template (e.g. a +SUM+ over line items) go
32
+ # stale once you write the inputs. When any cell was edited, {#save} sets
33
+ # <tt><calcPr fullCalcOnLoad="1"/></tt> in +xl/workbook.xml+ so Excel and
34
+ # LibreOffice recompute on open; pass <tt>recalc: false</tt> to skip it.
35
+ # If an edit replaced a formula with a value, +xl/calcChain.xml+ is
36
+ # dropped (Excel rebuilds it) so it never points at a non-formula cell.
37
+ #
38
+ # == Out of scope
39
+ #
40
+ # * inserting / deleting rows or columns
41
+ # * deleting / renaming / reordering / duplicating sheets ({#add_sheet}
42
+ # appends a new empty sheet)
43
+ # * editing formulas, defined names, drawings, or shared strings
28
44
  # * recomputing the worksheet +<dimension>+ when a write expands the bounds
29
45
  #
30
46
  # == Strings on write
@@ -97,6 +113,13 @@ module Rbxl
97
113
  @sheet_names = @sheet_entries.keys.freeze
98
114
  @shared_strings = nil
99
115
  @sheets_by_name = {}
116
+ @workbook_doc = nil
117
+ @workbook_rels_doc = nil
118
+ @content_types_doc = nil
119
+ @modified_parts = Set.new
120
+ @removed_parts = Set.new
121
+ @styles = nil
122
+ @date_1904 = nil
100
123
  end
101
124
 
102
125
  # Returns the editable worksheet for +name_or_index+. Repeated calls for
@@ -113,6 +136,7 @@ module Rbxl
113
136
 
114
137
  name = resolve_sheet_name(name_or_index)
115
138
  @sheets_by_name[name] ||= EditableWorksheet.new(
139
+ workbook: self,
116
140
  zip: @zip,
117
141
  entry_path: @sheet_entries.fetch(name) {
118
142
  raise SheetNotFoundError, "sheet not found: #{name}"
@@ -137,41 +161,148 @@ module Rbxl
137
161
  @sheet_names.each { |name| yield sheet(name) }
138
162
  end
139
163
 
164
+ # Appends a new, empty worksheet after the existing ones and returns it
165
+ # for editing. The sheet part, its workbook relationship, and its
166
+ # content-type override are created; nothing else in the package
167
+ # changes. (+docProps/app.xml+ keeps listing the old sheet titles;
168
+ # Excel and LibreOffice ignore that metadata on open.)
169
+ #
170
+ # @param name [String] sheet name (1–31 characters, none of
171
+ # <tt>[ ] : * ? / \\</tt>, not starting or ending with +'+, unique
172
+ # case-insensitively)
173
+ # @return [Rbxl::EditableWorksheet]
174
+ # @raise [ArgumentError] if +name+ is invalid or already taken
175
+ # @raise [Rbxl::ClosedWorkbookError] if the workbook has been closed
176
+ def add_sheet(name)
177
+ ensure_open!
178
+ validate_sheet_name!(name)
179
+
180
+ part = next_sheet_part_name
181
+ rid = add_workbook_relationship(SHEET_REL_TYPE, relative_target(part))
182
+ add_content_type_override(part, SHEET_CONTENT_TYPE)
183
+
184
+ sheets_node = workbook_doc.at_xpath("/main:workbook/main:sheets", "main" => MAIN_NS) or
185
+ raise WorkbookFormatError, "#{@path}: #{@workbook_part} has no <sheets>"
186
+ ids = XmlEdit.children(sheets_node, "sheet").map { |n| n["sheetId"].to_i }
187
+ prefix = relationship_prefix(workbook_doc)
188
+ XmlEdit.append(
189
+ sheets_node,
190
+ %(<sheet name="#{StyleXml.escape_attr(name)}" sheetId="#{(ids.max || 0) + 1}" #{prefix}:id="#{rid}"/>)
191
+ )
192
+ @modified_parts << @workbook_part
193
+
194
+ @sheet_entries[name] = part
195
+ @sheet_names = @sheet_entries.keys.freeze
196
+ @sheets_by_name[name] = EditableWorksheet.new(
197
+ workbook: self,
198
+ zip: @zip,
199
+ entry_path: part,
200
+ workbook_path: @path,
201
+ shared_strings: shared_strings,
202
+ name: name,
203
+ source_xml: EMPTY_SHEET_XML
204
+ )
205
+ end
206
+
207
+ # Registers a new cell style and returns its +style_id+ for
208
+ # {EditableCell#style_id=}. Accepts the same keywords as
209
+ # {WriteOnlyWorkbook#add_style}; unspecified components fall back to the
210
+ # workbook's defaults (entry 0). To change only part of a template
211
+ # cell's look, prefer {EditableCell#style}.
212
+ #
213
+ # red = book.add_style(font: { color: "C00000", bold: true })
214
+ # sheet["F20"].style_id = red
215
+ #
216
+ # @return [Integer] the new style's +cellXfs+ index
217
+ # @raise [Rbxl::ClosedWorkbookError] if the workbook has been closed
218
+ def add_style(font: nil, fill: nil, border: nil, alignment: nil, number_format: nil)
219
+ ensure_open!
220
+ styles.register(
221
+ Style.new(font: font, fill: fill, border: border, alignment: alignment, number_format: number_format)
222
+ )
223
+ end
224
+
225
+ # @return [Array<String>] defined names in workbook order (a name that
226
+ # exists both globally and sheet-locally is listed once)
227
+ # @raise [Rbxl::ClosedWorkbookError] if the workbook has been closed
228
+ def defined_names
229
+ ensure_open!
230
+ defined_name_nodes.map { |n| n["name"] }.uniq
231
+ end
232
+
233
+ # Resolves a defined name ("名前付きセル") that refers to a single cell
234
+ # and returns that cell, so templates can be filled by name instead of
235
+ # by coordinate:
236
+ #
237
+ # book.defined_name("顧客名").value = "株式会社Acme"
238
+ #
239
+ # Names match case-insensitively, as in Excel. A workbook-scoped name
240
+ # wins over sheet-scoped ones; pass +sheet:+ to pick a sheet-scoped name.
241
+ #
242
+ # @param name [String]
243
+ # @param sheet [String, Integer, nil] restrict to the name scoped to this
244
+ # sheet
245
+ # @return [Rbxl::EditableCell]
246
+ # @raise [Rbxl::DefinedNameError] if the name is missing, ambiguous, or
247
+ # refers to anything other than a single cell
248
+ # @raise [Rbxl::ClosedWorkbookError] if the workbook has been closed
249
+ def defined_name(name, sheet: nil)
250
+ ensure_open!
251
+ node = find_defined_name(name.to_s, sheet)
252
+ sheet_name, coordinate = parse_single_cell_reference(node)
253
+ unless @sheet_entries.key?(sheet_name)
254
+ raise DefinedNameError, "defined name #{name.inspect} refers to unknown sheet #{sheet_name.inspect}"
255
+ end
256
+
257
+ self.sheet(sheet_name).cell(coordinate)
258
+ end
259
+
140
260
  # Writes the workbook out, preserving every part that has not been
141
- # mutated byte-for-byte. Worksheets whose cells have been edited are
142
- # re-serialized from their in-memory Nokogiri document; all other
143
- # entries (styles, sharedStrings, drawings, charts, pivot caches,
144
- # custom XML, rels) are streamed straight from the source ZIP without
145
- # re-parsing.
261
+ # mutated byte-for-byte. Edited worksheets, and package parts changed by
262
+ # {#add_sheet} / {#add_style} / recalculation, are re-serialized from
263
+ # memory; all other entries (styles, sharedStrings, drawings, charts,
264
+ # pivot caches, custom XML, rels) are streamed straight from the source
265
+ # ZIP without re-parsing.
146
266
  #
147
267
  # +path+ defaults to the original load path; passing +nil+ or omitting
148
268
  # it saves in place. The new file is written to a temp file in the same
149
269
  # directory and atomically renamed into place, so a crash mid-write
150
- # never leaves a half-written workbook. On success, dirty flags on each
151
- # touched worksheet are cleared, so the object is reusable for further
152
- # edits and another {#save}.
270
+ # never leaves a half-written workbook. The object stays usable: further
271
+ # edits and saves include everything edited so far.
153
272
  #
154
273
  # @param path [String, #to_path, nil] destination path; defaults to the
155
274
  # path the workbook was opened from
275
+ # @param recalc [Boolean] when any cell was edited, ask Excel to
276
+ # recompute every formula on open (see "Recalculation" above)
156
277
  # @return [String] the path that was written
157
278
  # @raise [Rbxl::ClosedWorkbookError] if the workbook has been closed
158
- def save(path = nil)
279
+ def save(path = nil, recalc: true)
159
280
  ensure_open!
160
281
  out_path = (path || @path).to_s
161
- overrides = collect_overrides
282
+ prepare_workbook_parts(recalc)
283
+ parts = collect_parts
162
284
 
163
285
  tmp_path = "#{out_path}.rbxl-tmp.#{Process.pid}.#{rand(1 << 32).to_s(16)}"
164
286
  begin
165
287
  Zip::OutputStream.open(tmp_path) do |out|
288
+ written = Set.new
166
289
  @zip.each do |entry|
167
- next if entry.directory?
290
+ next if entry.directory? || @removed_parts.include?(entry.name)
168
291
 
169
- if (override_xml = overrides[entry.name])
292
+ if (xml = parts[entry.name])
170
293
  out.put_next_entry(entry.name)
171
- out.write(override_xml)
294
+ out.write(xml)
172
295
  else
173
296
  out.copy_raw_entry(entry)
174
297
  end
298
+ written << entry.name
299
+ end
300
+
301
+ parts.each do |name, xml|
302
+ next if written.include?(name)
303
+
304
+ out.put_next_entry(name)
305
+ out.write(xml)
175
306
  end
176
307
  end
177
308
  File.rename(tmp_path, out_path)
@@ -180,6 +311,7 @@ module Rbxl
180
311
  raise
181
312
  end
182
313
 
314
+ reopen_source! if File.expand_path(out_path) == File.expand_path(@path)
183
315
  @sheets_by_name.each_value(&:clear_dirty!)
184
316
  out_path
185
317
  end
@@ -274,10 +406,228 @@ module Rbxl
274
406
  @shared_strings ||= SharedStringsLoader.load(@zip)
275
407
  end
276
408
 
277
- def collect_overrides
278
- @sheets_by_name.each_with_object({}) do |(_, ws), h|
279
- h[ws.entry_path] = ws.to_xml if ws.dirty?
409
+ # @api private
410
+ # Lazily loaded, append-only view of the workbook's styles part. A
411
+ # minimal styles part is created when the workbook has none.
412
+ def styles
413
+ @styles ||= load_styles
414
+ end
415
+
416
+ # @api private
417
+ # @return [Boolean] whether the workbook uses the 1904 date system
418
+ def date_1904?
419
+ if @date_1904.nil?
420
+ pr = workbook_doc.at_xpath("/main:workbook/main:workbookPr", "main" => MAIN_NS)
421
+ @date_1904 = %w[1 true].include?(pr&.[]("date1904"))
422
+ end
423
+ @date_1904
424
+ end
425
+ public :styles, :date_1904?
426
+
427
+ SHEET_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet".freeze
428
+ STYLES_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles".freeze
429
+ CALC_CHAIN_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/calcChain".freeze
430
+ SHEET_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml".freeze
431
+ STYLES_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml".freeze
432
+ CONTENT_TYPES_PART = "[Content_Types].xml".freeze
433
+ CONTENT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types".freeze
434
+ private_constant :SHEET_REL_TYPE, :STYLES_REL_TYPE, :CALC_CHAIN_REL_TYPE,
435
+ :SHEET_CONTENT_TYPE, :STYLES_CONTENT_TYPE, :CONTENT_TYPES_PART, :CONTENT_TYPES_NS
436
+
437
+ EMPTY_SHEET_XML = <<~XML.freeze
438
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
439
+ <worksheet xmlns="#{MAIN_NS}" xmlns:r="#{REL_NS}"><sheetData/><pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/></worksheet>
440
+ XML
441
+ private_constant :EMPTY_SHEET_XML
442
+
443
+ # <workbook> child sequence (ECMA-376 part 1 §18.2.27), for calcPr.
444
+ WORKBOOK_ORDER = %w[fileVersion fileSharing workbookPr workbookProtection bookViews sheets
445
+ functionGroups externalReferences definedNames calcPr oleSize
446
+ customWorkbookViews pivotCaches smartTagPr smartTagTypes webPublishing
447
+ fileRecoveryPr webPublishObjects extLst].freeze
448
+ private_constant :WORKBOOK_ORDER
449
+
450
+ INVALID_SHEET_NAME_CHARS = %r{[\[\]:*?/\\]}.freeze
451
+ private_constant :INVALID_SHEET_NAME_CHARS
452
+
453
+ def load_styles
454
+ rel = workbook_rels_doc.xpath("/pkg:Relationships/pkg:Relationship", "pkg" => PACKAGE_REL_NS)
455
+ .find { |r| r["Type"] == STYLES_REL_TYPE }
456
+ if rel
457
+ part = resolve_relative(@workbook_dir, rel["Target"])
458
+ entry = @zip.find_entry(part) or raise WorkbookFormatError, "#{@path}: missing styles part #{part}"
459
+ EditableStyles.new(entry.get_input_stream.read, part_name: part, workbook_path: @path)
460
+ else
461
+ part = @workbook_dir == "." ? "styles.xml" : "#{@workbook_dir}/styles.xml"
462
+ add_workbook_relationship(STYLES_REL_TYPE, relative_target(part))
463
+ add_content_type_override(part, STYLES_CONTENT_TYPE)
464
+ @created_styles = true
465
+ EditableStyles.new(EditableStyles::MINIMAL_XML, part_name: part, workbook_path: @path)
466
+ end
467
+ end
468
+
469
+ def prepare_workbook_parts(recalc)
470
+ edited = @sheets_by_name.values.select(&:modified?)
471
+ drop_calc_chain! if edited.any?(&:formula_removed?)
472
+ request_full_calc_on_load! if recalc && edited.any?
473
+ end
474
+
475
+ def request_full_calc_on_load!
476
+ root = workbook_doc.root
477
+ calc_pr = XmlEdit.child(root, "calcPr") ||
478
+ XmlEdit.insert_in_order(root, "calcPr", "<calcPr/>", WORKBOOK_ORDER)
479
+ return if calc_pr["fullCalcOnLoad"] == "1"
480
+
481
+ calc_pr["fullCalcOnLoad"] = "1"
482
+ @modified_parts << @workbook_part
483
+ end
484
+
485
+ def drop_calc_chain!
486
+ rels = workbook_rels_doc.xpath("/pkg:Relationships/pkg:Relationship", "pkg" => PACKAGE_REL_NS)
487
+ .select { |r| r["Type"] == CALC_CHAIN_REL_TYPE }
488
+ return if rels.empty?
489
+
490
+ rels.each do |rel|
491
+ part = resolve_relative(@workbook_dir, rel["Target"])
492
+ @removed_parts << part
493
+ override = content_types_doc.root.element_children.find do |n|
494
+ n.name == "Override" && n["PartName"] == "/#{part}"
495
+ end
496
+ if override
497
+ override.unlink
498
+ @modified_parts << CONTENT_TYPES_PART
499
+ end
500
+ rel.unlink
501
+ end
502
+ @modified_parts << rels_path_for(@workbook_part)
503
+ end
504
+
505
+ def collect_parts
506
+ parts = {}
507
+ @sheets_by_name.each_value { |ws| parts[ws.entry_path] = ws.to_xml if ws.modified? }
508
+ parts[@styles.part_name] = @styles.to_xml if @styles && (@styles.modified? || @created_styles)
509
+ parts[@workbook_part] = XmlEdit.serialize(workbook_doc) if @modified_parts.include?(@workbook_part)
510
+ rels = rels_path_for(@workbook_part)
511
+ parts[rels] = XmlEdit.serialize(workbook_rels_doc) if @modified_parts.include?(rels)
512
+ parts[CONTENT_TYPES_PART] = XmlEdit.serialize(content_types_doc) if @modified_parts.include?(CONTENT_TYPES_PART)
513
+ parts
514
+ end
515
+
516
+ # rubyzip re-opens the archive by file name for every lazy read, so once
517
+ # an in-place save has replaced that file the old central directory no
518
+ # longer matches. Re-open and hand the fresh handle to every sheet.
519
+ def reopen_source!
520
+ @zip.close
521
+ @zip = Zip::File.open(@path)
522
+ @sheets_by_name.each_value { |ws| ws.rebind_zip!(@zip) }
523
+ @removed_parts.clear
524
+ end
525
+
526
+ def workbook_doc
527
+ @workbook_doc ||= parse_xml(@workbook_part)
528
+ end
529
+
530
+ def workbook_rels_doc
531
+ @workbook_rels_doc ||= begin
532
+ path = rels_path_for(@workbook_part)
533
+ if @zip.find_entry(path)
534
+ parse_xml(path)
535
+ else
536
+ Nokogiri::XML(%(<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<Relationships xmlns="#{PACKAGE_REL_NS}"/>))
537
+ end
538
+ end
539
+ end
540
+
541
+ def content_types_doc
542
+ @content_types_doc ||= parse_xml(CONTENT_TYPES_PART)
543
+ end
544
+
545
+ def add_workbook_relationship(type, target)
546
+ root = workbook_rels_doc.root
547
+ used = root.element_children.map { |r| r["Id"] }
548
+ n = used.filter_map { |id| id[/\ArId(\d+)\z/, 1]&.to_i }.max.to_i + 1
549
+ n += 1 while used.include?("rId#{n}")
550
+ rid = "rId#{n}"
551
+ XmlEdit.append(root, %(<Relationship Id="#{rid}" Type="#{type}" Target="#{StyleXml.escape_attr(target)}"/>))
552
+ @modified_parts << rels_path_for(@workbook_part)
553
+ rid
554
+ end
555
+
556
+ def add_content_type_override(part, content_type)
557
+ XmlEdit.append(content_types_doc.root,
558
+ %(<Override PartName="/#{StyleXml.escape_attr(part)}" ContentType="#{content_type}"/>))
559
+ @modified_parts << CONTENT_TYPES_PART
560
+ end
561
+
562
+ def relationship_prefix(doc)
563
+ prefix = doc.root.namespaces.find { |_, href| href == REL_NS }&.first&.delete_prefix("xmlns:")
564
+ return prefix if prefix && !prefix.empty? && prefix != "xmlns"
565
+
566
+ doc.root.add_namespace_definition("r", REL_NS)
567
+ "r"
568
+ end
569
+
570
+ def relative_target(part)
571
+ prefix = @workbook_dir == "." ? "" : "#{@workbook_dir}/"
572
+ part.start_with?(prefix) ? part.delete_prefix(prefix) : "/#{part}"
573
+ end
574
+
575
+ def next_sheet_part_name
576
+ dir = @workbook_dir == "." ? "worksheets" : "#{@workbook_dir}/worksheets"
577
+ taken = Set.new(@zip.entries.map(&:name)) | @sheet_entries.values
578
+ n = 1
579
+ n += 1 while taken.include?("#{dir}/sheet#{n}.xml")
580
+ "#{dir}/sheet#{n}.xml"
581
+ end
582
+
583
+ def validate_sheet_name!(name)
584
+ raise ArgumentError, "sheet name must be a String" unless name.is_a?(String)
585
+ raise ArgumentError, "sheet name must be 1-31 characters: #{name.inspect}" if name.empty? || name.length > 31
586
+ raise ArgumentError, "sheet name contains an invalid character ([]:*?/\\): #{name.inspect}" if name.match?(INVALID_SHEET_NAME_CHARS)
587
+ raise ArgumentError, "sheet name cannot start or end with an apostrophe: #{name.inspect}" if name.start_with?("'") || name.end_with?("'")
588
+ return unless @sheet_entries.keys.any? { |existing| existing.casecmp?(name) }
589
+
590
+ raise ArgumentError, "sheet already exists: #{name.inspect}"
591
+ end
592
+
593
+ def defined_name_nodes
594
+ workbook_doc.xpath("/main:workbook/main:definedNames/main:definedName", "main" => MAIN_NS).to_a
595
+ end
596
+
597
+ def find_defined_name(name, sheet)
598
+ matches = defined_name_nodes.select { |n| n["name"]&.casecmp?(name) }
599
+ raise DefinedNameError, "defined name not found: #{name.inspect}" if matches.empty?
600
+
601
+ if sheet
602
+ index = @sheet_entries.keys.index(resolve_sheet_name(sheet)) or
603
+ raise SheetNotFoundError, "sheet not found: #{sheet}"
604
+ found = matches.find { |n| n["localSheetId"]&.to_i == index }
605
+ return found if found
606
+
607
+ raise DefinedNameError, "defined name #{name.inspect} is not scoped to sheet #{sheet.inspect}"
608
+ end
609
+
610
+ global = matches.find { |n| n["localSheetId"].nil? }
611
+ return global if global
612
+ return matches.first if matches.length == 1
613
+
614
+ raise DefinedNameError,
615
+ "defined name #{name.inspect} exists on several sheets; pass sheet: to choose one"
616
+ end
617
+
618
+ SINGLE_CELL_REF_RE = /\A(?:'((?:[^']|'')+)'|([^'!]+))!\$?([A-Za-z]{1,3})\$?(\d+)(?::\$?([A-Za-z]{1,3})\$?(\d+))?\z/.freeze
619
+ private_constant :SINGLE_CELL_REF_RE
620
+
621
+ def parse_single_cell_reference(node)
622
+ ref = node.text.strip
623
+ m = ref.match(SINGLE_CELL_REF_RE)
624
+ single = m && (m[5].nil? || (m[5].casecmp?(m[3]) && m[6] == m[4]))
625
+ unless single
626
+ raise DefinedNameError, "defined name #{node['name'].inspect} refers to #{ref.inspect}, not a single cell"
280
627
  end
628
+
629
+ sheet_name = m[1] ? m[1].gsub("''", "'") : m[2]
630
+ [sheet_name, "#{m[3].upcase}#{m[4]}"]
281
631
  end
282
632
 
283
633
  def parse_xml(part_name)
@@ -11,6 +11,9 @@ module Rbxl
11
11
  # sheet["B5"].value = "company name"
12
12
  # sheet.cell("B5").value # => "company name"
13
13
  #
14
+ # Table-shaped regions (invoice line items, report rows) can be filled in
15
+ # one call with {#write_rows}.
16
+ #
14
17
  # See {EditableWorkbook} for the design contract these edits live inside.
15
18
  class EditableWorksheet
16
19
  # Namespace for the main SpreadsheetML schema.
@@ -22,21 +25,81 @@ module Rbxl
22
25
  # @return [String] ZIP entry path of the worksheet's XML part
23
26
  attr_reader :entry_path
24
27
 
28
+ # Largest column index Excel accepts (+XFD+).
29
+ MAX_COLUMN = 16_384
30
+
31
+ # Largest row number Excel accepts.
32
+ MAX_ROW = 1_048_576
33
+
34
+ # @api private
35
+ # Construct via {EditableWorkbook#sheet} / {EditableWorkbook#add_sheet}.
36
+ #
37
+ # @param workbook [Rbxl::EditableWorkbook] owning workbook
25
38
  # @param zip [Zip::File] open archive shared with the workbook
26
39
  # @param entry_path [String] ZIP entry path for this sheet's XML
27
40
  # @param workbook_path [String] filesystem path the workbook was opened from
28
41
  # @param shared_strings [Array<String>] pre-decoded shared strings table
29
42
  # @param name [String] visible sheet name
30
- def initialize(zip:, entry_path:, workbook_path:, shared_strings:, name:)
43
+ # @param source_xml [String, nil] initial XML for a sheet that does not
44
+ # exist in the source ZIP yet (see {EditableWorkbook#add_sheet})
45
+ def initialize(workbook:, zip:, entry_path:, workbook_path:, shared_strings:, name:, source_xml: nil)
46
+ @workbook = workbook
31
47
  @zip = zip
32
48
  @entry_path = entry_path
33
49
  @workbook_path = workbook_path
34
50
  @shared_strings = shared_strings
35
51
  @name = name
52
+ @source_xml = source_xml
36
53
  @doc = nil
37
54
  @sheet_data = nil
38
55
  @row_index = nil
39
56
  @dirty = false
57
+ @modified = !source_xml.nil?
58
+ @formula_removed = false
59
+ end
60
+
61
+ # Writes a 2D array of values into consecutive cells, top-left first.
62
+ # Each value goes through {EditableCell#value=}, so the template's
63
+ # per-cell styles are kept and +Date+ / +Time+ get date formatting.
64
+ # +nil+ entries clear the corresponding cell.
65
+ #
66
+ # Pass a range (e.g. <tt>"B10:D19"</tt>) instead of a single anchor to
67
+ # declare the template's capacity: writing more rows or wider rows than
68
+ # the range holds raises before any cell is touched. Rows are never
69
+ # inserted — growing a table past the template's prepared rows is out
70
+ # of scope.
71
+ #
72
+ # sheet.write_rows("B10:D19", [
73
+ # ["作業費", 1, 50_000],
74
+ # ["交通費", 1, 3_200],
75
+ # ])
76
+ #
77
+ # @param anchor [String] top-left coordinate, or an +A1:B2+-style range
78
+ # @param rows [Array<Array>] row-major values
79
+ # @return [Rbxl::EditableWorksheet] +self+
80
+ # @raise [ArgumentError] if the data does not fit the range or the sheet
81
+ def write_rows(anchor, rows)
82
+ raise ArgumentError, "rows must be an Array of Arrays" unless rows.is_a?(Array) && rows.all? { |r| r.is_a?(Array) }
83
+
84
+ start_col, start_row, max_rows, max_cols = parse_anchor(anchor)
85
+ width = rows.map(&:length).max || 0
86
+
87
+ if max_rows && rows.length > max_rows
88
+ raise ArgumentError, "#{rows.length} rows do not fit #{anchor} (#{max_rows} rows)"
89
+ end
90
+ if max_cols && width > max_cols
91
+ raise ArgumentError, "a #{width}-column row does not fit #{anchor} (#{max_cols} columns)"
92
+ end
93
+ if start_row + rows.length - 1 > MAX_ROW || start_col + width - 1 > MAX_COLUMN
94
+ raise ArgumentError, "data starting at #{anchor} extends past the sheet's bounds"
95
+ end
96
+
97
+ rows.each_with_index do |values, r|
98
+ values.each_with_index do |value, c|
99
+ cell("#{column_label(start_col + c)}#{start_row + r}").value = value
100
+ end
101
+ end
102
+ self
40
103
  end
41
104
 
42
105
  # Returns the {EditableCell} view for +coordinate+. Cells not present in
@@ -67,6 +130,42 @@ module Rbxl
67
130
  # @api private
68
131
  def mark_dirty!
69
132
  @dirty = true
133
+ @modified = true
134
+ end
135
+
136
+ # @api private
137
+ # Whether the in-memory XML differs from the source ZIP. Unlike {#dirty?}
138
+ # this survives {EditableWorkbook#save}: the source ZIP is never
139
+ # rewritten, so every later save must keep emitting the edited XML.
140
+ def modified?
141
+ @modified
142
+ end
143
+
144
+ # @api private
145
+ def note_formula_removed!
146
+ @formula_removed = true
147
+ end
148
+
149
+ # @api private
150
+ def formula_removed?
151
+ @formula_removed
152
+ end
153
+
154
+ # @api private
155
+ # Points lazy loads at a freshly reopened archive (after an in-place
156
+ # save replaced the file the old handle was reading by name).
157
+ def rebind_zip!(zip)
158
+ @zip = zip
159
+ end
160
+
161
+ # @api private
162
+ def styles
163
+ @workbook.styles
164
+ end
165
+
166
+ # @api private
167
+ def date_1904?
168
+ @workbook.date_1904?
70
169
  end
71
170
 
72
171
  # @api private
@@ -78,7 +177,7 @@ module Rbxl
78
177
  # The XML declaration and original namespace bindings are preserved.
79
178
  def to_xml
80
179
  ensure_doc_loaded!
81
- @doc.to_xml
180
+ XmlEdit.serialize(@doc)
82
181
  end
83
182
 
84
183
  # @api private
@@ -122,13 +221,7 @@ module Rbxl
122
221
  def ensure_doc_loaded!
123
222
  return if @doc
124
223
 
125
- entry = @zip.find_entry(@entry_path)
126
- unless entry
127
- raise WorksheetFormatError,
128
- "worksheet #{@name.inspect} is missing XML entry #{@entry_path.inspect} in #{@workbook_path}"
129
- end
130
-
131
- parsed = Nokogiri::XML(entry.get_input_stream.read)
224
+ parsed = Nokogiri::XML(@source_xml || read_entry)
132
225
  unless parsed.errors.empty?
133
226
  raise WorksheetFormatError,
134
227
  "invalid worksheet XML for sheet #{@name.inspect} in #{@workbook_path}: #{parsed.errors.first}"
@@ -148,6 +241,16 @@ module Rbxl
148
241
  end
149
242
  end
150
243
 
244
+ def read_entry
245
+ entry = @zip.find_entry(@entry_path)
246
+ unless entry
247
+ raise WorksheetFormatError,
248
+ "worksheet #{@name.inspect} is missing XML entry #{@entry_path.inspect} in #{@workbook_path}"
249
+ end
250
+
251
+ entry.get_input_stream.read
252
+ end
253
+
151
254
  def find_or_create_row(row_num, create:)
152
255
  existing = @row_index[row_num]
153
256
  return existing if existing
@@ -166,8 +269,7 @@ module Rbxl
166
269
  child.name == "row" && (child["r"]&.to_i || 0) > row_num
167
270
  end
168
271
  xml = %(<row r="#{row_num}"/>)
169
- added = following ? following.add_previous_sibling(xml) : parent.add_child(xml)
170
- first_node(added)
272
+ following ? XmlEdit.insert_before(following, xml) : XmlEdit.append(parent, xml)
171
273
  end
172
274
 
173
275
  def insert_cell_in_order(parent, coordinate, col_index)
@@ -178,12 +280,7 @@ module Rbxl
178
280
  child_col && child_col > col_index
179
281
  end
180
282
  xml = %(<c r="#{coordinate}"/>)
181
- added = following ? following.add_previous_sibling(xml) : parent.add_child(xml)
182
- first_node(added)
183
- end
184
-
185
- def first_node(result)
186
- result.is_a?(Nokogiri::XML::NodeSet) ? result.first : result
283
+ following ? XmlEdit.insert_before(following, xml) : XmlEdit.append(parent, xml)
187
284
  end
188
285
 
189
286
  COORDINATE_RE = /\A([A-Z]+)([1-9]\d*)\z/.freeze
@@ -207,6 +304,35 @@ module Rbxl
207
304
  [column_index(m[1]), m[2].to_i]
208
305
  end
209
306
 
307
+ RANGE_RE = /\A([A-Z]+)([1-9]\d*)(?::([A-Z]+)([1-9]\d*))?\z/.freeze
308
+ private_constant :RANGE_RE
309
+
310
+ # @return [Array(Integer, Integer, Integer|nil, Integer|nil)]
311
+ # start column, start row, and the range's row / column capacity
312
+ def parse_anchor(anchor)
313
+ m = anchor.to_s.upcase.match(RANGE_RE)
314
+ raise ArgumentError, "invalid anchor: #{anchor.inspect}" unless m
315
+
316
+ col1 = column_index(m[1])
317
+ row1 = m[2].to_i
318
+ return [col1, row1, nil, nil] unless m[3]
319
+
320
+ col2 = column_index(m[3])
321
+ row2 = m[4].to_i
322
+ raise ArgumentError, "range must run top-left to bottom-right: #{anchor.inspect}" if col2 < col1 || row2 < row1
323
+
324
+ [col1, row1, row2 - row1 + 1, col2 - col1 + 1]
325
+ end
326
+
327
+ def column_label(index)
328
+ label = +""
329
+ while index.positive?
330
+ index, rem = (index - 1).divmod(26)
331
+ label.prepend((65 + rem).chr)
332
+ end
333
+ label
334
+ end
335
+
210
336
  def column_index(label)
211
337
  col = 0
212
338
  label.each_byte { |b| col = (col * 26) + (b - 64) }