xlsxrb 0.1.17 → 0.2.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +256 -1
- data/README.md +111 -28
- data/lib/ruby_lsp/xlsxrb/completion_listener.rb +439 -139
- data/lib/xlsxrb/chart_builder.rb +540 -193
- data/lib/xlsxrb/dsl_helpers.rb +178 -73
- data/lib/xlsxrb/elements/cell.rb +197 -130
- data/lib/xlsxrb/elements/column.rb +88 -7
- data/lib/xlsxrb/elements/coordinate_access.rb +86 -59
- data/lib/xlsxrb/elements/image.rb +18 -19
- data/lib/xlsxrb/elements/metadata.rb +2379 -0
- data/lib/xlsxrb/elements/row.rb +84 -118
- data/lib/xlsxrb/elements/styles.rb +140 -90
- data/lib/xlsxrb/elements/types.rb +164 -22
- data/lib/xlsxrb/elements/workbook.rb +122 -140
- data/lib/xlsxrb/elements/worksheet.rb +451 -226
- data/lib/xlsxrb/elements.rb +1 -0
- data/lib/xlsxrb/ooxml/reader/listeners/core_listeners.rb +16 -5
- data/lib/xlsxrb/ooxml/reader/listeners/drawing_listeners.rb +14 -9
- data/lib/xlsxrb/ooxml/reader/listeners/feature_listeners.rb +296 -34
- data/lib/xlsxrb/ooxml/reader/listeners/style_listeners.rb +17 -3
- data/lib/xlsxrb/ooxml/reader.rb +52 -50
- data/lib/xlsxrb/ooxml/styles_parser.rb +36 -5
- data/lib/xlsxrb/ooxml/utils.rb +2 -2
- data/lib/xlsxrb/ooxml/workbook_parser.rb +0 -1
- data/lib/xlsxrb/ooxml/workbook_writer.rb +242 -109
- data/lib/xlsxrb/ooxml/worksheet_parser.rb +63 -31
- data/lib/xlsxrb/ooxml/worksheet_writer.rb +119 -56
- data/lib/xlsxrb/ooxml/writer/drawing_xml.rb +33 -13
- data/lib/xlsxrb/ooxml/writer/features_xml.rb +75 -15
- data/lib/xlsxrb/ooxml/writer/styles_xml.rb +18 -8
- data/lib/xlsxrb/ooxml/writer.rb +124 -44
- data/lib/xlsxrb/ooxml/xml_parser.rb +78 -5
- data/lib/xlsxrb/ooxml/zip_generator.rb +2 -0
- data/lib/xlsxrb/ooxml/zip_reader.rb +112 -25
- data/lib/xlsxrb/ooxml/zip_writer.rb +119 -30
- data/lib/xlsxrb/stream_row.rb +56 -81
- data/lib/xlsxrb/stream_sheet.rb +542 -273
- data/lib/xlsxrb/stream_writer.rb +1536 -870
- data/lib/xlsxrb/style_builder.rb +667 -221
- data/lib/xlsxrb/version.rb +1 -1
- data/lib/xlsxrb/workbook_builder.rb +406 -143
- data/lib/xlsxrb/worksheet_builder.rb +1009 -900
- data/lib/xlsxrb.rb +1179 -1056
- data/sig/generated/xlsxrb/chart_builder.rbs +385 -159
- data/sig/generated/xlsxrb/dsl_helpers.rbs +81 -15
- data/sig/generated/xlsxrb/elements/cell.rbs +78 -70
- data/sig/generated/xlsxrb/elements/column.rbs +55 -3
- data/sig/generated/xlsxrb/elements/coordinate_access.rbs +35 -29
- data/sig/generated/xlsxrb/elements/image.rbs +7 -11
- data/sig/generated/xlsxrb/elements/metadata.rbs +1574 -0
- data/sig/generated/xlsxrb/elements/row.rbs +39 -42
- data/sig/generated/xlsxrb/elements/styles.rbs +66 -66
- data/sig/generated/xlsxrb/elements/types.rbs +27 -0
- data/sig/generated/xlsxrb/elements/workbook.rbs +46 -99
- data/sig/generated/xlsxrb/elements/worksheet.rbs +121 -96
- data/sig/generated/xlsxrb/ooxml/reader/listeners/feature_listeners.rbs +61 -4
- data/sig/generated/xlsxrb/ooxml/reader.rbs +2 -2
- data/sig/generated/xlsxrb/ooxml/styles_parser.rbs +1 -1
- data/sig/generated/xlsxrb/ooxml/utils.rbs +3 -3
- data/sig/generated/xlsxrb/ooxml/workbook_writer.rbs +13 -1
- data/sig/generated/xlsxrb/ooxml/worksheet_parser.rbs +16 -0
- data/sig/generated/xlsxrb/ooxml/worksheet_writer.rbs +6 -4
- data/sig/generated/xlsxrb/ooxml/writer/features_xml.rbs +7 -0
- data/sig/generated/xlsxrb/ooxml/writer.rbs +22 -13
- data/sig/generated/xlsxrb/ooxml/xml_parser.rbs +70 -0
- data/sig/generated/xlsxrb/ooxml/zip_generator.rbs +2 -0
- data/sig/generated/xlsxrb/ooxml/zip_reader.rbs +24 -9
- data/sig/generated/xlsxrb/ooxml/zip_writer.rbs +26 -1
- data/sig/generated/xlsxrb/stream_row.rbs +32 -33
- data/sig/generated/xlsxrb/stream_sheet.rbs +233 -181
- data/sig/generated/xlsxrb/stream_writer.rbs +961 -667
- data/sig/generated/xlsxrb/style_builder.rbs +402 -128
- data/sig/generated/xlsxrb/workbook_builder.rbs +223 -71
- data/sig/generated/xlsxrb/worksheet_builder.rbs +579 -453
- data/sig/generated/xlsxrb.rbs +205 -144
- data/sig/rexml.rbs +8 -0
- metadata +5 -5
- data/lib/xlsxrb/utils.rb +0 -291
- data/sig/generated/xlsxrb/utils.rbs +0 -184
data/lib/xlsxrb.rb
CHANGED
|
@@ -35,11 +35,10 @@ require_relative "xlsxrb/worksheet_builder"
|
|
|
35
35
|
require_relative "xlsxrb/workbook_builder"
|
|
36
36
|
require_relative "xlsxrb/number_formatter"
|
|
37
37
|
require_relative "xlsxrb/stream_writer"
|
|
38
|
-
require_relative "xlsxrb/utils"
|
|
39
38
|
|
|
40
39
|
# Modern, streaming-capable, low-memory XLSX reading and writing library for Ruby.
|
|
41
40
|
#
|
|
42
|
-
# Provides high-level facade methods ({Xlsxrb.read}, {Xlsxrb.write}, {Xlsxrb.build}, {Xlsxrb.
|
|
41
|
+
# Provides high-level facade methods ({Xlsxrb.read}, {Xlsxrb.write}, {Xlsxrb.build}, {Xlsxrb.load})
|
|
43
42
|
# with full ECMA-376 OpenXML compliance, MS-OFFCRYPTO password protection, and zero core dependencies.
|
|
44
43
|
#
|
|
45
44
|
# @api public
|
|
@@ -48,22 +47,35 @@ module Xlsxrb
|
|
|
48
47
|
MAX_ROW = 1_048_576
|
|
49
48
|
|
|
50
49
|
# Maximum number of columns supported by Excel / OpenXML.
|
|
51
|
-
|
|
50
|
+
MAX_COLUMN = 16_384
|
|
52
51
|
|
|
53
52
|
# Maximum number of individual cell/range references allowed in a single data validation element by Excel.
|
|
54
53
|
MAX_REFS_PER_VALIDATION = 32_767
|
|
55
54
|
|
|
55
|
+
# <workbookProtection> attributes and the Elements::WorkbookProtection members they load into.
|
|
56
|
+
WORKBOOK_PROTECTION_ATTRIBUTES = {
|
|
57
|
+
"workbookPassword" => %i[workbook_password string],
|
|
58
|
+
"lockStructure" => %i[lock_structure bool],
|
|
59
|
+
"lockWindows" => %i[lock_windows bool],
|
|
60
|
+
"lockRevision" => %i[lock_revision bool],
|
|
61
|
+
"revisionsPassword" => %i[revisions_password string],
|
|
62
|
+
"workbookAlgorithmName" => %i[algorithm_name string],
|
|
63
|
+
"workbookHashValue" => %i[hash_value string],
|
|
64
|
+
"workbookSaltValue" => %i[salt_value string],
|
|
65
|
+
"workbookSpinCount" => %i[spin_count int],
|
|
66
|
+
"revisionsAlgorithmName" => %i[revisions_algorithm_name string],
|
|
67
|
+
"revisionsHashValue" => %i[revisions_hash_value string],
|
|
68
|
+
"revisionsSaltValue" => %i[revisions_salt_value string],
|
|
69
|
+
"revisionsSpinCount" => %i[revisions_spin_count int]
|
|
70
|
+
}.transform_values(&:freeze).freeze
|
|
71
|
+
private_constant :WORKBOOK_PROTECTION_ATTRIBUTES
|
|
72
|
+
|
|
73
|
+
# ZIP deflate level used when no compression_level is given.
|
|
74
|
+
# See docs/adr/0009-default-zip-compression-level.md.
|
|
75
|
+
DEFAULT_COMPRESSION_LEVEL = 1
|
|
76
|
+
|
|
56
77
|
# Base class for all exceptions raised by Xlsxrb.
|
|
57
|
-
|
|
58
|
-
class Error < StandardError
|
|
59
|
-
DIV0 = Elements::CellError.new(code: "#DIV/0!")
|
|
60
|
-
NA = Elements::CellError.new(code: "#N/A")
|
|
61
|
-
NAME = Elements::CellError.new(code: "#NAME?")
|
|
62
|
-
NULL = Elements::CellError.new(code: "#NULL!")
|
|
63
|
-
NUM = Elements::CellError.new(code: "#NUM!")
|
|
64
|
-
REF = Elements::CellError.new(code: "#REF!")
|
|
65
|
-
VALUE = Elements::CellError.new(code: "#VALUE!")
|
|
66
|
-
end
|
|
78
|
+
class Error < StandardError; end
|
|
67
79
|
|
|
68
80
|
# Raised when parsing malformed or invalid XML structures.
|
|
69
81
|
class ParseError < Error; end
|
|
@@ -89,7 +101,7 @@ module Xlsxrb
|
|
|
89
101
|
xl/dialogsheets/
|
|
90
102
|
xl/macrosheets/
|
|
91
103
|
].freeze
|
|
92
|
-
private_constant :OMITTED_TARGET, :OFFICE_DOC_REL_TYPES, :NON_WORKSHEET_REL_SUFFIXES, :NON_WORKSHEET_TARGET_PREFIXES
|
|
104
|
+
private_constant :OMITTED_TARGET, :VALID_SHEET_STATES, :OFFICE_DOC_REL_TYPES, :NON_WORKSHEET_REL_SUFFIXES, :NON_WORKSHEET_TARGET_PREFIXES
|
|
93
105
|
|
|
94
106
|
# Raised when cell, row, or workbook parameters fail specification validation.
|
|
95
107
|
class ValidationError < Error; end
|
|
@@ -200,19 +212,16 @@ module Xlsxrb
|
|
|
200
212
|
# @param type [Symbol, String, nil] Formula type (:shared, :array, etc.).
|
|
201
213
|
# @param ref [String, nil] Target cell or range reference (e.g. "A1:C1").
|
|
202
214
|
# @param shared_index [Integer, nil] Shared formula group index (0-based).
|
|
203
|
-
# @param si [Integer, nil] Alias for shared_index.
|
|
204
215
|
# @return [Elements::Formula]
|
|
205
216
|
# @api public
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
def self.formula(expression, cached_value: nil, type: nil, ref: nil, shared_index: nil, si: nil)
|
|
209
|
-
s_idx = shared_index || si
|
|
217
|
+
#: (String expression, ?cached_value: (String | Numeric | bool | Elements::CellError | nil), ?type: (Symbol | String)?, ?ref: String?, ?shared_index: Integer?) -> Elements::Formula
|
|
218
|
+
def self.formula(expression, cached_value: nil, type: nil, ref: nil, shared_index: nil)
|
|
210
219
|
Elements::Formula.new(
|
|
211
220
|
expression: expression,
|
|
212
221
|
cached_value: cached_value,
|
|
213
|
-
type: type || (
|
|
222
|
+
type: type || (shared_index ? :shared : nil),
|
|
214
223
|
ref: ref,
|
|
215
|
-
shared_index:
|
|
224
|
+
shared_index: shared_index,
|
|
216
225
|
calculate_always: cached_value.nil? || nil
|
|
217
226
|
)
|
|
218
227
|
end
|
|
@@ -220,51 +229,53 @@ module Xlsxrb
|
|
|
220
229
|
# Creates a shared formula {Elements::Formula} object for master or follower cell.
|
|
221
230
|
#
|
|
222
231
|
# @example Create a shared formula master
|
|
223
|
-
# formula = Xlsxrb.shared_formula("A2*2",
|
|
232
|
+
# formula = Xlsxrb.shared_formula("A2*2", shared_index: 0, ref: "B2:B10")
|
|
224
233
|
#
|
|
225
234
|
# @example Create a shared formula follower
|
|
226
|
-
# formula = Xlsxrb.shared_formula(
|
|
235
|
+
# formula = Xlsxrb.shared_formula(shared_index: 0)
|
|
227
236
|
#
|
|
228
237
|
# @param expression [String, nil] The formula expression (nil for follower cells).
|
|
229
|
-
# @param
|
|
238
|
+
# @param shared_index [Integer, nil] Shared formula group index (0-based).
|
|
230
239
|
# @param ref [String, nil] Target range for master cell (e.g. "B2:B10").
|
|
231
240
|
# @param cached_value [Object, nil] Optional precomputed value.
|
|
232
241
|
# @return [Elements::Formula]
|
|
233
242
|
# @api public
|
|
234
|
-
#: (?String? expression,
|
|
235
|
-
def self.shared_formula(expression = nil,
|
|
243
|
+
#: (?String? expression, ?shared_index: Integer?, ?ref: String?, ?cached_value: (String | Numeric | bool | Elements::CellError | nil)) -> Elements::Formula
|
|
244
|
+
def self.shared_formula(expression = nil, shared_index: nil, ref: nil, cached_value: nil)
|
|
245
|
+
raise ArgumentError, "shared_index is required for shared formula" if shared_index.nil?
|
|
246
|
+
|
|
236
247
|
Elements::Formula.new(
|
|
237
248
|
expression: expression || "",
|
|
238
249
|
cached_value: cached_value,
|
|
239
250
|
type: :shared,
|
|
240
251
|
ref: ref,
|
|
241
|
-
shared_index:
|
|
252
|
+
shared_index: shared_index,
|
|
242
253
|
calculate_always: cached_value.nil? || nil
|
|
243
254
|
)
|
|
244
255
|
end
|
|
245
|
-
# rubocop:enable Naming/MethodParameterName
|
|
246
256
|
|
|
247
257
|
# Creates an array or dynamic array {Elements::Formula} object.
|
|
248
258
|
#
|
|
249
259
|
# @example Create a multi-cell array formula
|
|
250
|
-
# formula = Xlsxrb.array_formula("SUM(B1:B10*C1:C10)", "A1:C1", cached_value: 0)
|
|
260
|
+
# formula = Xlsxrb.array_formula("SUM(B1:B10*C1:C10)", ref: "A1:C1", cached_value: 0)
|
|
251
261
|
#
|
|
252
262
|
# @example Create a dynamic array formula
|
|
253
|
-
# formula = Xlsxrb.array_formula("SORT(UNIQUE(A1:A10))", "D1")
|
|
263
|
+
# formula = Xlsxrb.array_formula("SORT(UNIQUE(A1:A10))", ref: "D1")
|
|
254
264
|
#
|
|
255
265
|
# @param expression [String] The formula expression without leading '='.
|
|
256
|
-
# @param ref [String, nil] Target cell or range reference (
|
|
266
|
+
# @param ref [String, nil] Target cell or range reference (keyword).
|
|
257
267
|
# @param cached_value [Object, nil] Optional precomputed value.
|
|
258
268
|
# @return [Elements::Formula]
|
|
259
269
|
# @api public
|
|
260
|
-
#: (String expression, ?String
|
|
261
|
-
def self.array_formula(expression, ref
|
|
270
|
+
#: (String expression, ?ref: String?, ?cached_value: (String | Numeric | bool | Elements::CellError | nil), **untyped attrs) -> Elements::Formula
|
|
271
|
+
def self.array_formula(expression, ref: nil, cached_value: nil, **attrs)
|
|
262
272
|
Elements::Formula.new(
|
|
263
273
|
expression: expression,
|
|
264
274
|
cached_value: cached_value,
|
|
265
275
|
type: :array,
|
|
266
276
|
ref: ref,
|
|
267
|
-
calculate_always: cached_value.nil? || nil
|
|
277
|
+
calculate_always: cached_value.nil? || nil,
|
|
278
|
+
**attrs
|
|
268
279
|
)
|
|
269
280
|
end
|
|
270
281
|
|
|
@@ -287,6 +298,50 @@ module Xlsxrb
|
|
|
287
298
|
Elements::Hyperlink.new(url: url, display: display, tooltip: tooltip, location: location)
|
|
288
299
|
end
|
|
289
300
|
|
|
301
|
+
# Creates an {Elements::Comment} object for use in cell comments.
|
|
302
|
+
#
|
|
303
|
+
# @example Create a cell comment
|
|
304
|
+
# comment = Xlsxrb.comment("Review this value", author: "Auditor")
|
|
305
|
+
#
|
|
306
|
+
# @param text [String, nil] Comment body text.
|
|
307
|
+
# @param author [String] Comment author.
|
|
308
|
+
# @param visible [Boolean] Whether comment is visible by default.
|
|
309
|
+
# @param ref [String, nil] Cell coordinate (e.g. "A1").
|
|
310
|
+
# @return [Elements::Comment]
|
|
311
|
+
# @api public
|
|
312
|
+
#: (?String? text, ?author: String, ?visible: bool, ?ref: String?, **untyped extra) -> Elements::Comment
|
|
313
|
+
def self.comment(text = nil, author: "Author", visible: false, ref: nil, **extra)
|
|
314
|
+
Elements::Comment.new(text: text, author: author, visible: visible, ref: ref, **extra)
|
|
315
|
+
end
|
|
316
|
+
|
|
317
|
+
# Creates or returns an {Elements::CellError} object.
|
|
318
|
+
#
|
|
319
|
+
# @example
|
|
320
|
+
# err = Xlsxrb.cell_error("#VALUE!")
|
|
321
|
+
# err = Xlsxrb.cell_error(:value)
|
|
322
|
+
#
|
|
323
|
+
# @param code [String, Symbol, Elements::CellError] Error code or symbol.
|
|
324
|
+
# @return [Elements::CellError]
|
|
325
|
+
# @api public
|
|
326
|
+
#: (String | Symbol | Elements::CellError code) -> Elements::CellError
|
|
327
|
+
def self.cell_error(code)
|
|
328
|
+
return code if code.is_a?(Elements::CellError)
|
|
329
|
+
|
|
330
|
+
code_str = code.to_s
|
|
331
|
+
error_map = {
|
|
332
|
+
null: "#NULL!",
|
|
333
|
+
div0: "#DIV/0!",
|
|
334
|
+
value: "#VALUE!",
|
|
335
|
+
ref: "#REF!",
|
|
336
|
+
name: "#NAME?",
|
|
337
|
+
num: "#NUM!",
|
|
338
|
+
na: "#N/A",
|
|
339
|
+
getting_data: "#GETTING_DATA"
|
|
340
|
+
}
|
|
341
|
+
resolved_code = error_map[code.to_sym] || code_str
|
|
342
|
+
Elements::CellError.new(code: resolved_code)
|
|
343
|
+
end
|
|
344
|
+
|
|
290
345
|
# Formats a cell value according to an Excel format code string.
|
|
291
346
|
#
|
|
292
347
|
# @param value [Object, nil] Value to format.
|
|
@@ -295,7 +350,7 @@ module Xlsxrb
|
|
|
295
350
|
# @return [String] Formatted string representation.
|
|
296
351
|
# @api public
|
|
297
352
|
#: (untyped value, ?String? format_code, ?date1904: bool) -> String
|
|
298
|
-
def self.
|
|
353
|
+
def self.format_value(value, format_code = nil, date1904: false)
|
|
299
354
|
NumberFormatter.format(value, format_code, date1904: date1904)
|
|
300
355
|
end
|
|
301
356
|
|
|
@@ -310,7 +365,11 @@ module Xlsxrb
|
|
|
310
365
|
# @api public
|
|
311
366
|
#: (Date | Time date_or_time, ?date1904: bool) -> (Integer | Float)
|
|
312
367
|
def self.date_to_serial(date_or_time, date1904: false)
|
|
313
|
-
|
|
368
|
+
if date_or_time.is_a?(Time) || date_or_time.is_a?(DateTime)
|
|
369
|
+
Ooxml::Utils.datetime_to_serial(date_or_time, date1904: date1904)
|
|
370
|
+
else
|
|
371
|
+
Ooxml::Utils.date_to_serial(date_or_time, date1904: date1904)
|
|
372
|
+
end
|
|
314
373
|
end
|
|
315
374
|
|
|
316
375
|
# Checks whether a serial number is a valid Excel date within the supported range.
|
|
@@ -325,7 +384,7 @@ module Xlsxrb
|
|
|
325
384
|
# @api public
|
|
326
385
|
#: (untyped serial, ?date1904: bool) -> bool
|
|
327
386
|
def self.valid_excel_date?(serial, date1904: false)
|
|
328
|
-
Utils.valid_excel_date?(serial, date1904: date1904)
|
|
387
|
+
Ooxml::Utils.valid_excel_date?(serial, date1904: date1904)
|
|
329
388
|
end
|
|
330
389
|
|
|
331
390
|
# Converts an Excel serial number to a Date.
|
|
@@ -339,21 +398,25 @@ module Xlsxrb
|
|
|
339
398
|
# @api public
|
|
340
399
|
#: (Numeric serial, ?date1904: bool) -> Date
|
|
341
400
|
def self.serial_to_date(serial, date1904: false)
|
|
342
|
-
Utils.serial_to_date(serial, date1904: date1904)
|
|
401
|
+
Ooxml::Utils.serial_to_date(serial, date1904: date1904)
|
|
343
402
|
end
|
|
344
403
|
|
|
345
404
|
# Converts a Time or Date to a fractional Excel serial number.
|
|
346
405
|
#
|
|
347
406
|
# @example
|
|
348
|
-
# Xlsxrb.
|
|
407
|
+
# Xlsxrb.time_to_serial(Time.utc(2026, 1, 1, 12, 0, 0)) #=> 46023.5
|
|
349
408
|
#
|
|
350
409
|
# @param time [Time, Date] Time or Date instance.
|
|
351
410
|
# @param date1904 [Boolean] Whether to use the 1904 date system.
|
|
352
411
|
# @return [Float] Fractional serial number.
|
|
353
412
|
# @api public
|
|
354
413
|
#: (Time | Date time, ?date1904: bool) -> Float
|
|
355
|
-
def self.
|
|
356
|
-
|
|
414
|
+
def self.time_to_serial(time, date1904: false)
|
|
415
|
+
if time.is_a?(Time) || time.is_a?(DateTime)
|
|
416
|
+
Ooxml::Utils.datetime_to_serial(time, date1904: date1904)
|
|
417
|
+
else
|
|
418
|
+
Ooxml::Utils.date_to_serial(time, date1904: date1904).to_f
|
|
419
|
+
end
|
|
357
420
|
end
|
|
358
421
|
|
|
359
422
|
# Converts an Excel serial number to a Time (UTC).
|
|
@@ -367,11 +430,64 @@ module Xlsxrb
|
|
|
367
430
|
# @api public
|
|
368
431
|
#: (Numeric serial, ?date1904: bool) -> Time
|
|
369
432
|
def self.serial_to_time(serial, date1904: false)
|
|
370
|
-
Utils.
|
|
433
|
+
Ooxml::Utils.serial_to_datetime(serial, date1904: date1904)
|
|
371
434
|
end
|
|
372
435
|
|
|
373
|
-
|
|
374
|
-
|
|
436
|
+
# Converts a cell reference string (e.g. "A1", "BC100") to 0-based [row, col] coordinates.
|
|
437
|
+
#
|
|
438
|
+
# @example
|
|
439
|
+
# Xlsxrb.parse_ref("A1") #=> [0, 0]
|
|
440
|
+
# Xlsxrb.parse_ref("BC100") #=> [99, 54]
|
|
441
|
+
#
|
|
442
|
+
# @param ref [String, nil] Excel cell reference string.
|
|
443
|
+
# @return [Array(Integer, Integer), nil] 0-based [row, col] tuple, or nil if invalid.
|
|
444
|
+
# @api public
|
|
445
|
+
#: (String? ref) -> [Integer, Integer]?
|
|
446
|
+
def self.parse_ref(ref)
|
|
447
|
+
Elements::Cell._parse_ref(ref)
|
|
448
|
+
end
|
|
449
|
+
|
|
450
|
+
# Converts 0-based [row, col] coordinates to an A1-style reference string.
|
|
451
|
+
#
|
|
452
|
+
# @example
|
|
453
|
+
# Xlsxrb.cell_to_ref(0, 0) #=> "A1"
|
|
454
|
+
# Xlsxrb.cell_to_ref(99, 54) #=> "BC100"
|
|
455
|
+
#
|
|
456
|
+
# @param row [Integer] 0-based row index.
|
|
457
|
+
# @param column [Integer] 0-based column index.
|
|
458
|
+
# @return [String] A1-style reference string.
|
|
459
|
+
# @api public
|
|
460
|
+
#: (Integer row, Integer column) -> String
|
|
461
|
+
def self.cell_to_ref(row, column)
|
|
462
|
+
"#{Elements::Cell._column_letter(column)}#{row + 1}"
|
|
463
|
+
end
|
|
464
|
+
|
|
465
|
+
# Converts a column letter (e.g. "A", :AA) to a 0-based column index.
|
|
466
|
+
#
|
|
467
|
+
# @example
|
|
468
|
+
# Xlsxrb.column_index("A") #=> 0
|
|
469
|
+
# Xlsxrb.column_index(:AA) #=> 26
|
|
470
|
+
#
|
|
471
|
+
# @param col [String, Symbol, Integer] Column letter or integer index.
|
|
472
|
+
# @return [Integer] 0-based column index.
|
|
473
|
+
# @api public
|
|
474
|
+
#: (String | Symbol | Integer col) -> Integer
|
|
475
|
+
def self.column_index(col)
|
|
476
|
+
Elements::Cell._column_index(col)
|
|
477
|
+
end
|
|
478
|
+
|
|
479
|
+
# Converts a 0-based column index to an Excel letter (0 -> "A", 25 -> "Z", 26 -> "AA").
|
|
480
|
+
#
|
|
481
|
+
# @example
|
|
482
|
+
# Xlsxrb.column_letter(0) #=> "A"
|
|
483
|
+
# Xlsxrb.column_letter(26) #=> "AA"
|
|
484
|
+
#
|
|
485
|
+
# @param index [Integer] 0-based column index.
|
|
486
|
+
# @return [String] Excel column letter.
|
|
487
|
+
# @api public
|
|
488
|
+
#: (Integer index) -> String
|
|
489
|
+
def self.column_letter(index)
|
|
490
|
+
Elements::Cell._column_letter(index)
|
|
375
491
|
end
|
|
376
492
|
|
|
377
493
|
# Converts a cell range reference string (e.g. "A1:C10", "A1") to 0-based [[top_row, left_col], [bottom_row, right_col]].
|
|
@@ -384,23 +500,144 @@ module Xlsxrb
|
|
|
384
500
|
# @api public
|
|
385
501
|
#: (String? range_ref) -> [[Integer, Integer], [Integer, Integer]]?
|
|
386
502
|
def self.parse_range(range_ref)
|
|
387
|
-
|
|
503
|
+
return nil if range_ref.nil? || range_ref.empty?
|
|
504
|
+
|
|
505
|
+
parts = range_ref.split(":", 2)
|
|
506
|
+
first = Elements::Cell._parse_ref(parts[0])
|
|
507
|
+
return nil unless first
|
|
508
|
+
|
|
509
|
+
second = parts[1] ? Elements::Cell._parse_ref(parts[1]) : first
|
|
510
|
+
return nil unless second
|
|
511
|
+
|
|
512
|
+
top_row = [first[0], second[0]].min
|
|
513
|
+
bottom_row = [first[0], second[0]].max
|
|
514
|
+
left_col = [first[1], second[1]].min
|
|
515
|
+
right_col = [first[1], second[1]].max
|
|
516
|
+
[[top_row, left_col], [bottom_row, right_col]]
|
|
388
517
|
end
|
|
389
518
|
|
|
390
519
|
# Converts 0-based bounding coordinates to an A1-style range reference string.
|
|
520
|
+
# Accepts either 4 flat integers (top_row, left_column, bottom_row, right_column)
|
|
521
|
+
# or a nested pair ([[top_row, left_column], [bottom_row, right_column]]) as returned by parse_range.
|
|
391
522
|
#
|
|
392
|
-
# @example
|
|
523
|
+
# @example 4 flat integers
|
|
393
524
|
# Xlsxrb.range_to_ref(0, 0, 9, 2) #=> "A1:C10"
|
|
394
525
|
#
|
|
395
|
-
# @
|
|
396
|
-
#
|
|
397
|
-
#
|
|
398
|
-
# @param
|
|
399
|
-
# @
|
|
526
|
+
# @example Nested pair from parse_range
|
|
527
|
+
# Xlsxrb.range_to_ref([[0, 0], [9, 2]]) #=> "A1:C10"
|
|
528
|
+
#
|
|
529
|
+
# @param top_row_or_bounds [Integer, Array] 0-based start row index or nested bounding coordinates.
|
|
530
|
+
# @param left_column [Integer, nil] 0-based start column index.
|
|
531
|
+
# @param bottom_row [Integer, nil] 0-based end row index.
|
|
532
|
+
# @param right_column [Integer, nil] 0-based end column index.
|
|
533
|
+
# @return [String] A1-style range reference string.
|
|
534
|
+
# @api public
|
|
535
|
+
#: (Integer | [[Integer, Integer], [Integer, Integer]] top_row_or_bounds, ?Integer? left_column, ?Integer? bottom_row, ?Integer? right_column) -> String
|
|
536
|
+
def self.range_to_ref(top_row_or_bounds, left_column = nil, bottom_row = nil, right_column = nil)
|
|
537
|
+
if top_row_or_bounds.is_a?(Array)
|
|
538
|
+
first, second = top_row_or_bounds
|
|
539
|
+
top_row = first[0]
|
|
540
|
+
left_col = first[1]
|
|
541
|
+
bot_row = second[0]
|
|
542
|
+
rgt_col = second[1]
|
|
543
|
+
else
|
|
544
|
+
top_row = top_row_or_bounds
|
|
545
|
+
left_col = left_column || 0
|
|
546
|
+
bot_row = bottom_row || top_row
|
|
547
|
+
rgt_col = right_column || left_col
|
|
548
|
+
end
|
|
549
|
+
if top_row == bot_row && left_col == rgt_col
|
|
550
|
+
cell_to_ref(top_row, left_col)
|
|
551
|
+
else
|
|
552
|
+
"#{cell_to_ref(top_row, left_col)}:#{cell_to_ref(bot_row, rgt_col)}"
|
|
553
|
+
end
|
|
554
|
+
end
|
|
555
|
+
|
|
556
|
+
# Splits an A1-style cell reference into its column name and 1-based row number.
|
|
557
|
+
#
|
|
558
|
+
# @example
|
|
559
|
+
# Xlsxrb.split_coordinate("A1") #=> ["A", 1]
|
|
560
|
+
# Xlsxrb.split_coordinate("BC100") #=> ["BC", 100]
|
|
561
|
+
#
|
|
562
|
+
# @param cell_ref [String, nil] Excel cell reference string.
|
|
563
|
+
# @return [Array(String, Integer), nil] [col_name, row_number] tuple (1-based row), or nil if invalid.
|
|
564
|
+
# @api public
|
|
565
|
+
#: (String? cell_ref) -> [String, Integer]?
|
|
566
|
+
def self.split_coordinate(cell_ref)
|
|
567
|
+
return nil unless cell_ref
|
|
568
|
+
|
|
569
|
+
coords = Elements::Cell._parse_ref(cell_ref)
|
|
570
|
+
return nil unless coords
|
|
571
|
+
|
|
572
|
+
row_idx, col_idx = coords
|
|
573
|
+
[Elements::Cell._column_letter(col_idx), row_idx + 1]
|
|
574
|
+
end
|
|
575
|
+
|
|
576
|
+
FORMULA_TOKEN_RE = %r{(?<str>"(?:[^"]|"")*")|(?<ref>(?<=\b|\A|[$!:,()+\-*/^<>=& \r\n])(?<col_abs>\$?)(?<col>[A-Za-z]{1,3})(?<row_abs>\$?)(?<row>\d+)(?!\w|\())}
|
|
577
|
+
private_constant :FORMULA_TOKEN_RE
|
|
578
|
+
|
|
579
|
+
# Expands a formula by shifting relative cell references from a master cell to a target cell or by offset amounts.
|
|
580
|
+
#
|
|
581
|
+
# @example Shift formula down one row
|
|
582
|
+
# Xlsxrb.expand_formula("A2*2", row_delta: 1, column_delta: 0) #=> "A3*2"
|
|
583
|
+
# Xlsxrb.expand_formula("A2*2", from_ref: "B2", to_ref: "B3") #=> "A3*2"
|
|
584
|
+
#
|
|
585
|
+
# @example Shift formula with absolute references
|
|
586
|
+
# Xlsxrb.expand_formula("$A$1+A2", row_delta: 2, column_delta: 0) #=> "$A$1+A4"
|
|
587
|
+
#
|
|
588
|
+
# @param formula [String, nil] Formula expression to expand.
|
|
589
|
+
# @param from_ref [String, nil] Master cell reference (e.g. "B2").
|
|
590
|
+
# @param to_ref [String, nil] Target cell reference (e.g. "B3").
|
|
591
|
+
# @param row_delta [Integer, nil] Row shift amount (positive = down, negative = up).
|
|
592
|
+
# @param column_delta [Integer, nil] Column shift amount (positive = right, negative = left).
|
|
593
|
+
# @return [String, nil] Expanded formula expression.
|
|
400
594
|
# @api public
|
|
401
|
-
#: (
|
|
402
|
-
def self.
|
|
403
|
-
|
|
595
|
+
#: (String? formula, ?from_ref: String?, ?to_ref: String?, ?row_delta: Integer?, ?column_delta: Integer?) -> String?
|
|
596
|
+
def self.expand_formula(formula, from_ref: nil, to_ref: nil, row_delta: nil, column_delta: nil)
|
|
597
|
+
return formula if formula.nil? || formula.empty?
|
|
598
|
+
|
|
599
|
+
if from_ref && to_ref
|
|
600
|
+
f_coords = Elements::Cell._parse_ref(from_ref)
|
|
601
|
+
t_coords = Elements::Cell._parse_ref(to_ref)
|
|
602
|
+
return formula unless f_coords && t_coords
|
|
603
|
+
|
|
604
|
+
rd = t_coords[0] - f_coords[0]
|
|
605
|
+
cd = t_coords[1] - f_coords[1]
|
|
606
|
+
else
|
|
607
|
+
rd = row_delta || 0
|
|
608
|
+
cd = column_delta || 0
|
|
609
|
+
end
|
|
610
|
+
|
|
611
|
+
return formula if rd.zero? && cd.zero?
|
|
612
|
+
|
|
613
|
+
formula.gsub(FORMULA_TOKEN_RE) do |match|
|
|
614
|
+
m = Regexp.last_match
|
|
615
|
+
if m[:str]
|
|
616
|
+
match
|
|
617
|
+
else
|
|
618
|
+
c_abs = !m[:col_abs].empty?
|
|
619
|
+
r_abs = !m[:row_abs].empty?
|
|
620
|
+
col = m[:col]
|
|
621
|
+
row = m[:row].to_i
|
|
622
|
+
|
|
623
|
+
new_col = if c_abs || cd.zero?
|
|
624
|
+
col
|
|
625
|
+
else
|
|
626
|
+
ci = Elements::Cell._column_index(col) + cd
|
|
627
|
+
ci = ci.clamp(0, 16_383)
|
|
628
|
+
Elements::Cell._column_letter(ci)
|
|
629
|
+
end
|
|
630
|
+
|
|
631
|
+
new_row = if r_abs || rd.zero?
|
|
632
|
+
row
|
|
633
|
+
else
|
|
634
|
+
ri = row + rd
|
|
635
|
+
ri.clamp(1, 1_048_576)
|
|
636
|
+
end
|
|
637
|
+
|
|
638
|
+
"#{m[:col_abs]}#{new_col}#{m[:row_abs]}#{new_row}"
|
|
639
|
+
end
|
|
640
|
+
end
|
|
404
641
|
end
|
|
405
642
|
|
|
406
643
|
# Resolves an ECMA-376 indexed color palette index (0..63) to an RRGGBB hex string (or AARRGGBB if alpha: true).
|
|
@@ -435,10 +672,6 @@ module Xlsxrb
|
|
|
435
672
|
Colors.to_hex(color, alpha: alpha)
|
|
436
673
|
end
|
|
437
674
|
|
|
438
|
-
class << self
|
|
439
|
-
alias color_to_hex to_hex_color
|
|
440
|
-
end
|
|
441
|
-
|
|
442
675
|
# Sanitizes a worksheet name to ensure it conforms to Excel constraints within 31 characters.
|
|
443
676
|
# Replaces forbidden characters (\ / ? * [ ] : and control characters),
|
|
444
677
|
# replaces leading/trailing apostrophes, and replaces reserved 'History' with 'History_'.
|
|
@@ -456,35 +689,11 @@ module Xlsxrb
|
|
|
456
689
|
DslHelpers.sanitize_sheet_name(name, replace_char: replace_char)
|
|
457
690
|
end
|
|
458
691
|
|
|
459
|
-
class << self
|
|
460
|
-
alias sheet_name sanitize_sheet_name
|
|
461
|
-
end
|
|
462
|
-
|
|
463
692
|
# Reads an XLSX file (streaming and lazy-loaded by default) from a file path, IO stream, or binary String.
|
|
464
693
|
#
|
|
465
694
|
# Sheets and rows are streamed lazily with O(1) constant memory. If a block is given,
|
|
466
|
-
# yields each {StreamSheet} sequentially. Call {#load}
|
|
467
|
-
#
|
|
468
|
-
#
|
|
469
|
-
# @overload read(source, password: nil, trim_empty_rows: false, pad_empty_rows: false, pad_empty_cells: false, &block)
|
|
470
|
-
# Yields each {StreamSheet} sequentially in streaming mode.
|
|
471
|
-
# @param source [String, IO, StringIO] File path, binary content string, or readable IO stream.
|
|
472
|
-
# @param password [String, nil] Optional password to decrypt password-protected XLSX files.
|
|
473
|
-
# @param trim_empty_rows [Boolean] Whether to omit trailing empty rows during sheet iteration.
|
|
474
|
-
# @param pad_empty_rows [Boolean] Whether to yield empty rows for skipped row numbers.
|
|
475
|
-
# @param pad_empty_cells [Boolean] Whether to pad missing cells within rows.
|
|
476
|
-
# @yield [sheet]
|
|
477
|
-
# @yieldparam sheet [StreamSheet] The streaming worksheet object.
|
|
478
|
-
# @return [void]
|
|
479
|
-
#
|
|
480
|
-
# @overload read(source, password: nil, trim_empty_rows: false, pad_empty_rows: false, pad_empty_cells: false)
|
|
481
|
-
# Returns a lazy {Elements::Workbook} object.
|
|
482
|
-
# @param source [String, IO, StringIO] File path, binary content string, or readable IO stream.
|
|
483
|
-
# @param password [String, nil] Optional password to decrypt password-protected XLSX files.
|
|
484
|
-
# @param trim_empty_rows [Boolean] Whether to omit trailing empty rows during sheet iteration.
|
|
485
|
-
# @param pad_empty_rows [Boolean] Whether to yield empty rows for skipped row numbers.
|
|
486
|
-
# @param pad_empty_cells [Boolean] Whether to pad missing cells within rows.
|
|
487
|
-
# @return [Elements::Workbook]
|
|
695
|
+
# yields each {StreamSheet} sequentially. Call {StreamSheet#load} to convert a sheet to
|
|
696
|
+
# an in-memory representation for coordinate random access (`sheet["A1"]`).
|
|
488
697
|
#
|
|
489
698
|
# @example Streaming read across sheets and rows (O(1) constant memory)
|
|
490
699
|
# Xlsxrb.read("large.xlsx") do |sheet|
|
|
@@ -494,25 +703,30 @@ module Xlsxrb
|
|
|
494
703
|
# end
|
|
495
704
|
# end
|
|
496
705
|
#
|
|
497
|
-
# @
|
|
498
|
-
#
|
|
499
|
-
#
|
|
500
|
-
#
|
|
501
|
-
#
|
|
502
|
-
#
|
|
706
|
+
# @param source [String, IO, StringIO] File path, binary content string, or readable IO stream.
|
|
707
|
+
# @param password [String, nil] Optional password to decrypt password-protected XLSX files.
|
|
708
|
+
# @param trim_empty_rows [Boolean] Whether to omit trailing empty rows during sheet iteration.
|
|
709
|
+
# @param pad_empty_rows [Boolean] Whether to yield empty rows for skipped row numbers.
|
|
710
|
+
# @param pad_empty_cells [Boolean] Whether to pad missing cells within rows.
|
|
503
711
|
# @param max_uncompressed_size [Integer, nil] Maximum allowed uncompressed size in bytes per entry (ZIP bomb defense).
|
|
712
|
+
# @yield [sheet]
|
|
713
|
+
# @yieldparam sheet [StreamSheet] The streaming worksheet object.
|
|
714
|
+
# @return [Enumerator<StreamSheet>, void]
|
|
504
715
|
# @raise [ZipBombError] If an uncompressed entry exceeds max_uncompressed_size.
|
|
505
716
|
# @raise [EncryptedFileError] If the file is encrypted and no password was supplied.
|
|
506
717
|
# @raise [InvalidPasswordError] If the supplied password is incorrect.
|
|
507
718
|
# @raise [ParseError] If the spreadsheet XML structure is invalid.
|
|
508
719
|
# @api public
|
|
509
720
|
#: (untyped source, ?password: String?, ?trim_empty_rows: bool, ?pad_empty_rows: bool, ?pad_empty_cells: bool, ?max_uncompressed_size: Integer?) { (StreamSheet) -> void } -> void
|
|
510
|
-
#: (untyped source, ?password: String?, ?trim_empty_rows: bool, ?pad_empty_rows: bool, ?pad_empty_cells: bool, ?max_uncompressed_size: Integer?) ->
|
|
721
|
+
#: (untyped source, ?password: String?, ?trim_empty_rows: bool, ?pad_empty_rows: bool, ?pad_empty_cells: bool, ?max_uncompressed_size: Integer?) -> Enumerator[StreamSheet, void]
|
|
511
722
|
def self.read(source, password: nil, trim_empty_rows: false, pad_empty_rows: false, pad_empty_cells: false, max_uncompressed_size: nil, &)
|
|
512
723
|
prepared_source = prepare_source_io(source, password)
|
|
724
|
+
return to_enum(:read, source, password: password, trim_empty_rows: trim_empty_rows, pad_empty_rows: pad_empty_rows, pad_empty_cells: pad_empty_cells, max_uncompressed_size: max_uncompressed_size) unless block_given?
|
|
725
|
+
|
|
513
726
|
zip_options = {}
|
|
514
727
|
zip_options[:max_uncompressed_size] = max_uncompressed_size if max_uncompressed_size
|
|
515
728
|
zip_reader = Ooxml::ZipReader.open(prepared_source, **zip_options)
|
|
729
|
+
|
|
516
730
|
begin
|
|
517
731
|
workbook_path = resolve_workbook_entry(zip_reader)
|
|
518
732
|
wb_dir = File.dirname(workbook_path)
|
|
@@ -533,6 +747,87 @@ module Xlsxrb
|
|
|
533
747
|
workbook_sheets = wb_parsed[:sheets]
|
|
534
748
|
is_date1904 = wb_parsed[:date1904]
|
|
535
749
|
|
|
750
|
+
ws_idx = 0
|
|
751
|
+
workbook_sheets.each do |sheet_info|
|
|
752
|
+
r_id = sheet_info[:r_id]
|
|
753
|
+
target = rels[r_id]
|
|
754
|
+
rel_type = rel_types[r_id]
|
|
755
|
+
next if non_worksheet_relationship?(rel_type, target)
|
|
756
|
+
|
|
757
|
+
sheet_path = resolve_sheet_entry(zip_reader, target, wb_dir, ws_idx)
|
|
758
|
+
current_sheet_idx = ws_idx
|
|
759
|
+
ws_idx += 1
|
|
760
|
+
next unless sheet_path
|
|
761
|
+
|
|
762
|
+
chunk_supplier = ->(&blk) { zip_reader.each_entry_chunk(sheet_path, &blk) }
|
|
763
|
+
|
|
764
|
+
stream_sheet = StreamSheet.new(
|
|
765
|
+
sheet_info[:name],
|
|
766
|
+
chunk_supplier,
|
|
767
|
+
shared_strings,
|
|
768
|
+
styles,
|
|
769
|
+
zip_reader: zip_reader,
|
|
770
|
+
entry_name: sheet_path,
|
|
771
|
+
state: sheet_info[:state] || :visible,
|
|
772
|
+
date1904: is_date1904,
|
|
773
|
+
trim_empty_rows: trim_empty_rows,
|
|
774
|
+
pad_empty_rows: pad_empty_rows,
|
|
775
|
+
pad_empty_cells: pad_empty_cells,
|
|
776
|
+
defined_names: wb_parsed[:defined_names] || [],
|
|
777
|
+
sheet_index: current_sheet_idx
|
|
778
|
+
)
|
|
779
|
+
yield stream_sheet
|
|
780
|
+
end
|
|
781
|
+
nil
|
|
782
|
+
ensure
|
|
783
|
+
zip_reader&.close
|
|
784
|
+
end
|
|
785
|
+
end
|
|
786
|
+
|
|
787
|
+
# Loads all sheets into memory, returning an {Elements::Workbook} where every
|
|
788
|
+
# worksheet is a fully-parsed {Elements::Worksheet} supporting coordinate random access.
|
|
789
|
+
# The underlying zip resources are closed immediately.
|
|
790
|
+
#
|
|
791
|
+
# @example
|
|
792
|
+
# wb = Xlsxrb.load("report.xlsx")
|
|
793
|
+
# puts wb["Sheet1"]["A1"].value
|
|
794
|
+
#
|
|
795
|
+
# @param source [String, IO, StringIO] Path to the .xlsx file or an IO-like stream.
|
|
796
|
+
# @param password [String, nil] Password for decrypting password-protected (ECMA-376 Standard/Agile) workbooks.
|
|
797
|
+
# @param trim_empty_rows [Boolean] Whether to omit trailing empty rows from worksheet data.
|
|
798
|
+
# @param pad_empty_rows [Boolean] Whether to pad missing rows with empty row objects.
|
|
799
|
+
# @param pad_empty_cells [Boolean] Whether to pad missing cells within rows with nil cells.
|
|
800
|
+
# @param max_uncompressed_size [Integer, nil] Maximum uncompressed file size threshold in bytes for zip bomb protection.
|
|
801
|
+
# @return [Elements::Workbook] The fully loaded in-memory workbook.
|
|
802
|
+
# @api public
|
|
803
|
+
#: (untyped source, ?password: String?, ?trim_empty_rows: bool, ?pad_empty_rows: bool, ?pad_empty_cells: bool, ?max_uncompressed_size: Integer?) -> Elements::Workbook
|
|
804
|
+
def self.load(source, password: nil, trim_empty_rows: false, pad_empty_rows: false, pad_empty_cells: false, max_uncompressed_size: nil)
|
|
805
|
+
prepared_source = prepare_source_io(source, password)
|
|
806
|
+
zip_options = {}
|
|
807
|
+
zip_options[:max_uncompressed_size] = max_uncompressed_size if max_uncompressed_size
|
|
808
|
+
zip_reader = Ooxml::ZipReader.open(prepared_source, **zip_options)
|
|
809
|
+
|
|
810
|
+
begin
|
|
811
|
+
workbook_path = resolve_workbook_entry(zip_reader)
|
|
812
|
+
wb_dir = File.dirname(workbook_path)
|
|
813
|
+
wb_rels_name = wb_dir == "." ? "_rels/#{File.basename(workbook_path)}.rels" : "#{wb_dir}/_rels/#{File.basename(workbook_path)}.rels"
|
|
814
|
+
rels_xml = zip_reader.read_entry(wb_rels_name)
|
|
815
|
+
rels, rel_types = parse_workbook_relationships(rels_xml)
|
|
816
|
+
|
|
817
|
+
sst_entry = resolve_part_entry(zip_reader, rels, "sharedStrings", "sharedStrings.xml", wb_dir)
|
|
818
|
+
shared_strings_xml = sst_entry ? zip_reader.read_entry(sst_entry) : nil
|
|
819
|
+
shared_strings = shared_strings_xml ? Ooxml::SharedStringsParser.parse(shared_strings_xml) : []
|
|
820
|
+
|
|
821
|
+
styles_entry = resolve_part_entry(zip_reader, rels, "styles", "styles.xml", wb_dir)
|
|
822
|
+
styles_xml = styles_entry ? zip_reader.read_entry(styles_entry) : nil
|
|
823
|
+
styles = styles_xml ? Ooxml::StylesParser.parse(styles_xml) : {}
|
|
824
|
+
|
|
825
|
+
workbook_xml = zip_reader.read_entry(workbook_path)
|
|
826
|
+
wb_parsed = Ooxml::WorkbookParser.parse_with_properties(workbook_xml)
|
|
827
|
+
workbook_sheets = wb_parsed[:sheets]
|
|
828
|
+
is_date1904 = wb_parsed[:date1904]
|
|
829
|
+
defined_names = wb_parsed[:defined_names] || []
|
|
830
|
+
|
|
536
831
|
non_worksheet_sheets = []
|
|
537
832
|
ws_idx = 0
|
|
538
833
|
sheets = workbook_sheets.filter_map do |sheet_info|
|
|
@@ -545,30 +840,37 @@ module Xlsxrb
|
|
|
545
840
|
end
|
|
546
841
|
|
|
547
842
|
sheet_path = resolve_sheet_entry(zip_reader, target, wb_dir, ws_idx)
|
|
843
|
+
current_sheet_idx = ws_idx
|
|
548
844
|
ws_idx += 1
|
|
549
845
|
next unless sheet_path
|
|
550
846
|
|
|
551
|
-
|
|
847
|
+
sheet_xml = zip_reader.read_entry(sheet_path)
|
|
848
|
+
sheet_name = sheet_info[:name]
|
|
849
|
+
pa = extract_sheet_print_area(defined_names, sheet_name, current_sheet_idx)
|
|
850
|
+
pt = extract_sheet_print_titles(defined_names, sheet_name, current_sheet_idx)
|
|
552
851
|
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
852
|
+
build_worksheet(
|
|
853
|
+
sheet_name,
|
|
854
|
+
sheet_xml,
|
|
556
855
|
shared_strings,
|
|
557
856
|
styles,
|
|
857
|
+
state: sheet_info[:state] || :visible,
|
|
558
858
|
zip_reader: zip_reader,
|
|
559
859
|
entry_name: sheet_path,
|
|
560
|
-
state: sheet_info[:state] || :visible,
|
|
561
860
|
date1904: is_date1904,
|
|
562
861
|
trim_empty_rows: trim_empty_rows,
|
|
563
862
|
pad_empty_rows: pad_empty_rows,
|
|
564
|
-
pad_empty_cells: pad_empty_cells
|
|
863
|
+
pad_empty_cells: pad_empty_cells,
|
|
864
|
+
print_area: pa,
|
|
865
|
+
print_titles: pt
|
|
565
866
|
)
|
|
566
867
|
end
|
|
567
868
|
|
|
568
869
|
wb_unmapped = {}
|
|
569
870
|
wb_props = {}
|
|
570
871
|
wb_props[:date1904] = true if is_date1904
|
|
571
|
-
wb_props[:
|
|
872
|
+
wb_props[:active_sheet] = wb_parsed[:active_tab] unless wb_parsed[:active_tab].nil?
|
|
873
|
+
wb_props[:active_sheet_index] = wb_parsed[:active_tab] unless wb_parsed[:active_tab].nil?
|
|
572
874
|
wb_props[:first_sheet] = wb_parsed[:first_sheet] unless wb_parsed[:first_sheet].nil?
|
|
573
875
|
wb_props[:show_sheet_tabs] = wb_parsed[:show_sheet_tabs] unless wb_parsed[:show_sheet_tabs].nil?
|
|
574
876
|
wb_props[:tab_ratio] = wb_parsed[:tab_ratio] unless wb_parsed[:tab_ratio].nil?
|
|
@@ -581,8 +883,16 @@ module Xlsxrb
|
|
|
581
883
|
prot_match = workbook_xml.match(%r{<workbookProtection\b([^>]*)/>})
|
|
582
884
|
if prot_match
|
|
583
885
|
prot = {}
|
|
584
|
-
|
|
585
|
-
|
|
886
|
+
prot_match[1].scan(/([A-Za-z]+)="([^"]*)"/) do |attr, value|
|
|
887
|
+
key, kind = WORKBOOK_PROTECTION_ATTRIBUTES[attr]
|
|
888
|
+
next unless key
|
|
889
|
+
|
|
890
|
+
prot[key] = case kind
|
|
891
|
+
when :bool then %w[1 true].include?(value)
|
|
892
|
+
when :int then value.to_i
|
|
893
|
+
else value
|
|
894
|
+
end
|
|
895
|
+
end
|
|
586
896
|
wb_unmapped[:workbook_protection] = prot unless prot.empty?
|
|
587
897
|
end
|
|
588
898
|
end
|
|
@@ -607,30 +917,19 @@ module Xlsxrb
|
|
|
607
917
|
Ooxml::XmlParser.parse(custom_xml, cu_listener)
|
|
608
918
|
wb_unmapped[:custom_properties] = cu_listener.properties unless cu_listener.properties.empty?
|
|
609
919
|
end
|
|
610
|
-
|
|
611
|
-
|
|
920
|
+
|
|
921
|
+
Elements::Workbook.new(
|
|
612
922
|
sheets: sheets,
|
|
613
923
|
shared_strings: shared_strings,
|
|
614
924
|
styles: styles,
|
|
615
925
|
unmapped_data: wb_unmapped,
|
|
616
926
|
defined_names: defined_names
|
|
617
927
|
)
|
|
618
|
-
|
|
619
|
-
if block_given?
|
|
620
|
-
sheets.each(&)
|
|
621
|
-
nil
|
|
622
|
-
else
|
|
623
|
-
wb
|
|
624
|
-
end
|
|
625
928
|
ensure
|
|
626
|
-
zip_reader
|
|
929
|
+
zip_reader&.close
|
|
627
930
|
end
|
|
628
931
|
end
|
|
629
932
|
|
|
630
|
-
class << self
|
|
631
|
-
alias stream read
|
|
632
|
-
end
|
|
633
|
-
|
|
634
933
|
# Writes an XLSX file or IO stream (streaming or in-memory), or returns a binary string.
|
|
635
934
|
#
|
|
636
935
|
# @overload write(?target, password: nil, encryption_mode: :standard, strict_excel_mode: true, &block)
|
|
@@ -682,16 +981,16 @@ module Xlsxrb
|
|
|
682
981
|
# When set to `false`, strings are emitted directly as inline strings (`<c t="inlineStr">`), providing flat
|
|
683
982
|
# $O(1)$ constant memory during streaming write. Disabling shared strings is recommended when streaming
|
|
684
983
|
# large datasets where cells contain unique text (e.g. log exports, transaction details).
|
|
685
|
-
# @param compression_level [Integer, nil] ZIP deflate compression level (0..9, or Zlib::DEFAULT_COMPRESSION
|
|
686
|
-
#
|
|
687
|
-
#
|
|
688
|
-
#: (?untyped target_or_workbook, ?Elements::Workbook | untyped workbook_or_nil, ?password: String?, ?encryption_mode: Symbol, ?strict_excel_mode: bool, ?
|
|
689
|
-
def self.write(target_or_workbook = OMITTED_TARGET, workbook_or_nil = nil, password: nil, encryption_mode: :standard, strict_excel_mode: true,
|
|
984
|
+
# @param compression_level [Integer, nil] ZIP deflate compression level (0..9, or Zlib::DEFAULT_COMPRESSION
|
|
985
|
+
# for zlib's level 6). Defaults to {DEFAULT_COMPRESSION_LEVEL}. Higher levels write smaller files more slowly;
|
|
986
|
+
# level 0 stores entries without compression. See docs/adr/0009-default-zip-compression-level.md.
|
|
987
|
+
#: (?untyped target_or_workbook, ?Elements::Workbook | untyped workbook_or_nil, ?password: String?, ?encryption_mode: Symbol, ?strict_excel_mode: bool, ?default_font: untyped?, ?shared_strings: bool, ?compression_level: Integer | nil) ?{ (StreamWriter) -> void } -> untyped
|
|
988
|
+
def self.write(target_or_workbook = OMITTED_TARGET, workbook_or_nil = nil, password: nil, encryption_mode: :standard, strict_excel_mode: true, default_font: nil, shared_strings: true, compression_level: DEFAULT_COMPRESSION_LEVEL, &)
|
|
690
989
|
if block_given?
|
|
691
990
|
if target_or_workbook.equal?(OMITTED_TARGET)
|
|
692
991
|
io = StringIO.new
|
|
693
992
|
io.binmode
|
|
694
|
-
write(io, password: password, encryption_mode: encryption_mode, strict_excel_mode: strict_excel_mode,
|
|
993
|
+
write(io, password: password, encryption_mode: encryption_mode, strict_excel_mode: strict_excel_mode, default_font: default_font, shared_strings: shared_strings, compression_level: compression_level, &)
|
|
695
994
|
return io.string.b
|
|
696
995
|
end
|
|
697
996
|
|
|
@@ -701,7 +1000,7 @@ module Xlsxrb
|
|
|
701
1000
|
if password && !password.empty?
|
|
702
1001
|
buf = StringIO.new
|
|
703
1002
|
buf.binmode
|
|
704
|
-
stream_writer = StreamWriter.new(buf, strict_excel_mode: strict_excel_mode,
|
|
1003
|
+
stream_writer = StreamWriter.new(buf, strict_excel_mode: strict_excel_mode, default_font: default_font, shared_strings: shared_strings, compression_level: compression_level)
|
|
705
1004
|
begin
|
|
706
1005
|
yield stream_writer
|
|
707
1006
|
stream_writer.close
|
|
@@ -716,7 +1015,7 @@ module Xlsxrb
|
|
|
716
1015
|
stream_writer.cleanup!
|
|
717
1016
|
end
|
|
718
1017
|
else
|
|
719
|
-
stream_writer = StreamWriter.new(target, strict_excel_mode: strict_excel_mode,
|
|
1018
|
+
stream_writer = StreamWriter.new(target, strict_excel_mode: strict_excel_mode, default_font: default_font, shared_strings: shared_strings, compression_level: compression_level)
|
|
720
1019
|
begin
|
|
721
1020
|
yield stream_writer
|
|
722
1021
|
stream_writer.close
|
|
@@ -781,66 +1080,82 @@ module Xlsxrb
|
|
|
781
1080
|
style_idx = col.unmapped_data&.[](:style_index) || col.unmapped_data&.[](:style) || (col.respond_to?(:style_index) && col.style_index)
|
|
782
1081
|
min = col.unmapped_data&.[](:min)
|
|
783
1082
|
max = col.unmapped_data&.[](:max)
|
|
784
|
-
{ index: col.index, width: col.width, hidden: col.hidden
|
|
1083
|
+
{ index: col.index, width: col.width, hidden: col.hidden?, custom_width: col.custom_width?, outline_level: col.outline_level, style_index: style_idx, min: min, max: max }
|
|
785
1084
|
# simplecov:enable
|
|
786
1085
|
end
|
|
787
1086
|
sd = { name: ws.name, rows: ws.rows, columns: columns }
|
|
788
1087
|
sd[:charts] = ws.charts unless ws.charts.empty?
|
|
789
|
-
sd[:conditional_formats] = ws.
|
|
1088
|
+
sd[:conditional_formats] = ws.conditional_formats unless ws.conditional_formats.empty?
|
|
790
1089
|
sd[:data_validations] = ws.data_validations unless ws.data_validations.empty?
|
|
791
1090
|
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
facade&.each { |key, val| sd[key] ||= val }
|
|
795
|
-
|
|
796
|
-
sd[:state] ||= ws.state if ws.respond_to?(:state) && ws.state && ws.state != :visible
|
|
797
|
-
sd[:comments] ||= ws.comments if ws.respond_to?(:comments) && !ws.comments.empty?
|
|
1091
|
+
sd[:state] = ws.state if ws.respond_to?(:state) && ws.state && ws.state != :visible
|
|
1092
|
+
sd[:comments] = ws.comments if ws.respond_to?(:comments) && !ws.comments.empty?
|
|
798
1093
|
if ws.respond_to?(:hyperlinks) && !ws.hyperlinks.empty?
|
|
799
|
-
sd[:hyperlinks]
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
1094
|
+
sd[:hyperlinks] = if ws.hyperlinks.is_a?(Hash)
|
|
1095
|
+
ws.hyperlinks.map do |cell_ref, link|
|
|
1096
|
+
entry = if link.is_a?(Hash)
|
|
1097
|
+
link.dup
|
|
1098
|
+
else
|
|
1099
|
+
(link.respond_to?(:to_h) ? link.to_h : { url: link })
|
|
1100
|
+
end
|
|
1101
|
+
entry[:ref] ||= cell_ref
|
|
1102
|
+
entry
|
|
807
1103
|
end
|
|
1104
|
+
else
|
|
1105
|
+
ws.hyperlinks
|
|
1106
|
+
end
|
|
1107
|
+
end
|
|
1108
|
+
sd[:sparkline_groups] = ws.sparkline_groups if ws.respond_to?(:sparkline_groups) && !ws.sparkline_groups.empty?
|
|
1109
|
+
sd[:sheet_properties] = ws.sheet_properties if ws.respond_to?(:sheet_properties) && ws.sheet_properties && !ws.sheet_properties.empty?
|
|
1110
|
+
sd[:sheet_format] = ws.sheet_format if ws.respond_to?(:sheet_format) && ws.sheet_format && !ws.sheet_format.empty?
|
|
1111
|
+
sd[:protected_ranges] = ws.protected_ranges.map { |r| r.respond_to?(:to_h) ? r.to_h : r } if ws.respond_to?(:protected_ranges) && !ws.protected_ranges.empty?
|
|
1112
|
+
sd[:cell_watches] = ws.cell_watches.map { |w| w.respond_to?(:to_h) ? w.to_h : w } if ws.respond_to?(:cell_watches) && !ws.cell_watches.empty?
|
|
1113
|
+
sd[:ignored_errors] = ws.ignored_errors if ws.respond_to?(:ignored_errors) && !ws.ignored_errors.empty?
|
|
1114
|
+
sd[:phonetic_properties] = ws.phonetic_properties.respond_to?(:to_h) ? ws.phonetic_properties.to_h : ws.phonetic_properties if ws.respond_to?(:phonetic_properties) && ws.phonetic_properties
|
|
1115
|
+
sd[:sheet_calc_pr] = ws.sheet_calc_properties.respond_to?(:to_h) ? ws.sheet_calc_properties.to_h : ws.sheet_calc_properties if ws.respond_to?(:sheet_calc_properties) && ws.sheet_calc_properties
|
|
1116
|
+
sd[:freeze_pane] = ws.freeze_pane.respond_to?(:to_h) ? ws.freeze_pane.to_h : ws.freeze_pane if ws.respond_to?(:freeze_pane) && ws.freeze_pane
|
|
1117
|
+
sd[:split_pane] = ws.unmapped_data.dig(:facade, :split_pane) || (ws.split_pane.respond_to?(:to_h) ? ws.split_pane.to_h : ws.split_pane) if ws.respond_to?(:split_pane) && ws.split_pane
|
|
1118
|
+
sd[:sheet_view] = ws.sheet_view.respond_to?(:to_h) ? ws.sheet_view.to_h : ws.sheet_view if ws.respond_to?(:sheet_view) && ws.sheet_view && !ws.sheet_view.empty?
|
|
1119
|
+
if ws.respond_to?(:selection) && ws.selection
|
|
1120
|
+
sd[:selection] = if ws.selection.is_a?(Array)
|
|
1121
|
+
ws.selection.map { |sel| sel.respond_to?(:to_h) ? sel.to_h : sel }
|
|
1122
|
+
else
|
|
1123
|
+
ws.selection.respond_to?(:to_h) ? ws.selection.to_h : ws.selection
|
|
1124
|
+
end
|
|
808
1125
|
end
|
|
809
|
-
sd[:sparkline_groups] ||= ws.sparkline_groups if ws.respond_to?(:sparkline_groups) && !ws.sparkline_groups.empty?
|
|
810
|
-
sd[:sheet_properties] ||= ws.sheet_properties if ws.respond_to?(:sheet_properties) && !ws.sheet_properties.empty?
|
|
811
|
-
sd[:sheet_format] ||= ws.sheet_format if ws.respond_to?(:sheet_format) && !ws.sheet_format.empty?
|
|
812
|
-
sd[:protected_ranges] ||= ws.protected_ranges if ws.respond_to?(:protected_ranges) && !ws.protected_ranges.empty?
|
|
813
|
-
sd[:cell_watches] ||= ws.cell_watches if ws.respond_to?(:cell_watches) && !ws.cell_watches.empty?
|
|
814
|
-
sd[:ignored_errors] ||= ws.ignored_errors if ws.respond_to?(:ignored_errors) && !ws.ignored_errors.empty?
|
|
815
|
-
sd[:phonetic_properties] ||= ws.phonetic_properties if ws.respond_to?(:phonetic_properties) && ws.phonetic_properties
|
|
816
|
-
sd[:sheet_calc_pr] ||= ws.sheet_calc_pr if ws.respond_to?(:sheet_calc_pr) && ws.sheet_calc_pr
|
|
817
|
-
sd[:freeze_pane] ||= ws.freeze_pane if ws.respond_to?(:freeze_pane) && ws.freeze_pane
|
|
818
|
-
sd[:split_pane] ||= ws.split_pane if ws.respond_to?(:split_pane) && ws.split_pane
|
|
819
|
-
sd[:sheet_view] ||= ws.sheet_view if ws.respond_to?(:sheet_view) && ws.sheet_view && !ws.sheet_view.empty?
|
|
820
|
-
sd[:selection] ||= ws.selection if ws.respond_to?(:selection) && ws.selection
|
|
821
1126
|
sd[:selection] ||= ws.sheet_view[:selection] if ws.respond_to?(:sheet_view) && ws.sheet_view.is_a?(Hash) && ws.sheet_view[:selection]
|
|
822
|
-
sd[:page_setup]
|
|
823
|
-
sd[:page_margins]
|
|
824
|
-
sd[:header_footer]
|
|
825
|
-
sd[:print_options]
|
|
826
|
-
sd[:sheet_protection]
|
|
827
|
-
sd[:tables]
|
|
828
|
-
sd[:merge_cells]
|
|
829
|
-
sd[:auto_filter]
|
|
830
|
-
sd[:
|
|
831
|
-
sd[:
|
|
832
|
-
sd[:
|
|
1127
|
+
sd[:page_setup] = ws.page_setup.respond_to?(:to_h) ? ws.page_setup.to_h : ws.page_setup if ws.respond_to?(:page_setup) && ws.page_setup && !ws.page_setup.empty?
|
|
1128
|
+
sd[:page_margins] = ws.page_margins.respond_to?(:to_h) ? ws.page_margins.to_h : ws.page_margins if ws.respond_to?(:page_margins) && ws.page_margins && !ws.page_margins.empty?
|
|
1129
|
+
sd[:header_footer] = ws.header_footer.respond_to?(:to_h) ? ws.header_footer.to_h : ws.header_footer if ws.respond_to?(:header_footer) && ws.header_footer && !ws.header_footer.empty?
|
|
1130
|
+
sd[:print_options] = ws.print_options.respond_to?(:to_h) ? ws.print_options.to_h : ws.print_options if ws.respond_to?(:print_options) && ws.print_options && !ws.print_options.empty?
|
|
1131
|
+
sd[:sheet_protection] = ws.sheet_protection.respond_to?(:to_h) ? ws.sheet_protection.to_h : ws.sheet_protection if ws.respond_to?(:sheet_protection) && ws.sheet_protection && !ws.sheet_protection.empty?
|
|
1132
|
+
sd[:tables] = ws.tables.map { |t| t.respond_to?(:to_h) ? t.to_h : t } if ws.respond_to?(:tables) && ws.tables && !ws.tables.empty?
|
|
1133
|
+
sd[:merge_cells] = ws.merged_cells if ws.respond_to?(:merged_cells) && ws.merged_cells && !ws.merged_cells.empty?
|
|
1134
|
+
sd[:auto_filter] = ws.auto_filter if ws.respond_to?(:auto_filter) && ws.auto_filter
|
|
1135
|
+
sd[:filter_columns] = ws.unmapped_data.dig(:facade, :filter_columns) || (ws.filter_columns.transform_values { |fc| fc.respond_to?(:to_spec) ? fc.to_spec : fc } if ws.respond_to?(:filter_columns) && ws.filter_columns && !ws.filter_columns.empty?)
|
|
1136
|
+
sd[:sort_state] = ws.unmapped_data.dig(:facade, :sort_state) || (ws.sort_state.respond_to?(:to_h) ? ws.sort_state.to_h : ws.sort_state) if ws.respond_to?(:sort_state) && ws.sort_state
|
|
1137
|
+
sd[:pivot_tables] = ws.pivot_tables.map { |pt| pt.respond_to?(:to_h) ? pt.to_h : pt } if ws.respond_to?(:pivot_tables) && ws.pivot_tables && !ws.pivot_tables.empty?
|
|
1138
|
+
sd[:shapes] = ws.shapes.map { |s| s.respond_to?(:to_h) ? s.to_h : s } if ws.respond_to?(:shapes) && ws.shapes && !ws.shapes.empty?
|
|
1139
|
+
sd[:threaded_comments] = ws.threaded_comments if ws.respond_to?(:threaded_comments) && ws.threaded_comments && !ws.threaded_comments.empty?
|
|
1140
|
+
sd[:header_footer_images] = ws.header_footer_images if ws.respond_to?(:header_footer_images) && ws.header_footer_images && !ws.header_footer_images.empty?
|
|
1141
|
+
if ws.respond_to?(:row_breaks) && ws.row_breaks && !ws.row_breaks.empty?
|
|
1142
|
+
sd[:row_breaks] = ws.row_breaks.map { |r| r.respond_to?(:to_h) ? r.to_h : r }
|
|
1143
|
+
end
|
|
1144
|
+
if ws.respond_to?(:column_breaks) && ws.column_breaks && !ws.column_breaks.empty?
|
|
1145
|
+
sd[:column_breaks] = ws.column_breaks.map { |c| c.respond_to?(:to_h) ? c.to_h : c }
|
|
1146
|
+
end
|
|
1147
|
+
sd[:background_image] = ws.background_image if ws.respond_to?(:background_image) && ws.background_image
|
|
833
1148
|
if ws.respond_to?(:images) && ws.images && !ws.images.empty?
|
|
834
|
-
sd[:images]
|
|
1149
|
+
sd[:images] = ws.images.map do |img|
|
|
835
1150
|
if img.is_a?(Elements::Image)
|
|
836
1151
|
ext = img.filename ? File.extname(img.filename).delete_prefix(".").downcase : "png"
|
|
837
1152
|
opts = img.unmapped_data ? img.unmapped_data.dup : {}
|
|
838
1153
|
opts[:name] ||= img.name
|
|
839
1154
|
opts[:file_data] = img.data
|
|
840
1155
|
opts[:ext] = ext
|
|
841
|
-
opts[:
|
|
1156
|
+
opts[:from_column] = img.from_column
|
|
842
1157
|
opts[:from_row] = img.from_row
|
|
843
|
-
opts[:
|
|
1158
|
+
opts[:to_column] = img.to_column
|
|
844
1159
|
opts[:to_row] = img.to_row
|
|
845
1160
|
opts
|
|
846
1161
|
else
|
|
@@ -848,20 +1163,30 @@ module Xlsxrb
|
|
|
848
1163
|
end
|
|
849
1164
|
end
|
|
850
1165
|
end
|
|
851
|
-
sd[:shapes]
|
|
1166
|
+
sd[:shapes] = ws.shapes if ws.respond_to?(:shapes) && ws.shapes && !ws.shapes.empty?
|
|
1167
|
+
|
|
1168
|
+
# Extract facade metadata from unmapped_data as fallback
|
|
1169
|
+
facade = ws.unmapped_data[:facade] if ws.respond_to?(:unmapped_data) && ws.unmapped_data.is_a?(Hash)
|
|
1170
|
+
facade&.each { |key, val| sd[key] = val unless sd.key?(key) }
|
|
852
1171
|
|
|
853
1172
|
sd
|
|
854
1173
|
end
|
|
855
1174
|
|
|
856
1175
|
# Extract workbook-level facade metadata
|
|
857
1176
|
wb_facade = workbook.unmapped_data[:facade] || {}
|
|
858
|
-
wb_properties = workbook.unmapped_data[:workbook_properties] || wb_facade[:workbook_properties]
|
|
1177
|
+
wb_properties = (workbook.unmapped_data[:workbook_properties] || wb_facade[:workbook_properties] || {}).merge(
|
|
1178
|
+
workbook.respond_to?(:workbook_properties) && workbook.workbook_properties ? workbook.workbook_properties.to_h : {}
|
|
1179
|
+
)
|
|
859
1180
|
wb_core = (workbook.respond_to?(:core_properties) && workbook.core_properties) || wb_facade[:core_properties]
|
|
860
1181
|
wb_app = (workbook.respond_to?(:app_properties) && workbook.app_properties) || wb_facade[:app_properties]
|
|
861
1182
|
wb_custom = (workbook.respond_to?(:custom_properties) && workbook.custom_properties) || wb_facade[:custom_properties]
|
|
862
1183
|
wb_prot = (workbook.respond_to?(:workbook_protection) && workbook.workbook_protection) || wb_facade[:workbook_protection]
|
|
863
1184
|
raw_dns = wb_facade[:defined_names] || (workbook.respond_to?(:defined_names) && !workbook.defined_names.empty? ? workbook.defined_names : nil)
|
|
864
|
-
defined_names =
|
|
1185
|
+
defined_names = if raw_dns
|
|
1186
|
+
raw_dns.map { |dn| dn.is_a?(Elements::MetadataRecord) ? dn.to_h : dn.dup }
|
|
1187
|
+
else
|
|
1188
|
+
[]
|
|
1189
|
+
end
|
|
865
1190
|
|
|
866
1191
|
# Auto-generate _xlnm.Print_Area and _xlnm.Print_Titles from worksheet definitions if not already present
|
|
867
1192
|
workbook.sheets.each_with_index do |ws, idx|
|
|
@@ -873,8 +1198,10 @@ module Xlsxrb
|
|
|
873
1198
|
next unless ws.respond_to?(:print_titles) && ws.print_titles && defined_names.none? { |dn| dn[:name] == "_xlnm.Print_Titles" && (dn[:local_sheet_id] == idx || dn[:local_sheet_name] == sheet_name) }
|
|
874
1199
|
|
|
875
1200
|
pt = ws.print_titles
|
|
1201
|
+
pt = pt.to_h if pt.is_a?(Elements::MetadataRecord)
|
|
876
1202
|
parts = []
|
|
877
|
-
|
|
1203
|
+
col_val = pt[:columns]
|
|
1204
|
+
parts << "'#{sheet_name}'!$#{col_val.sub(":", ":$")}" if col_val
|
|
878
1205
|
parts << "'#{sheet_name}'!$#{pt[:rows].sub(":", ":$")}" if pt[:rows]
|
|
879
1206
|
defined_names << { name: "_xlnm.Print_Titles", value: parts.join(","), local_sheet_id: idx } unless parts.empty?
|
|
880
1207
|
end
|
|
@@ -921,223 +1248,6 @@ module Xlsxrb
|
|
|
921
1248
|
end
|
|
922
1249
|
end
|
|
923
1250
|
|
|
924
|
-
# Modifies an existing XLSX file in-memory using an immutable transformation block.
|
|
925
|
-
#
|
|
926
|
-
# Reads the workbook, passes it to the block, and writes the resulting workbook.
|
|
927
|
-
# If no target is specified, the source file is overwritten in-place.
|
|
928
|
-
#
|
|
929
|
-
# @example Modify a template and save to new file
|
|
930
|
-
# Xlsxrb.modify("template.xlsx", "output.xlsx") do |workbook|
|
|
931
|
-
# workbook.update_sheet("Sheet1") do |sheet|
|
|
932
|
-
# sheet.update_cell("B1", value: "Updated Title")
|
|
933
|
-
# .update_cell("B2", value: 100)
|
|
934
|
-
# end
|
|
935
|
-
# end
|
|
936
|
-
#
|
|
937
|
-
# @param source [String, IO, StringIO] The source file path or IO object.
|
|
938
|
-
# @param target [String, IO, StringIO, nil] Target file path or IO object (overwrites source if nil).
|
|
939
|
-
# @param password [String, nil] Optional password for encrypted files.
|
|
940
|
-
# @yield [workbook]
|
|
941
|
-
# @yieldparam workbook [Elements::Workbook] The loaded workbook.
|
|
942
|
-
# @yieldreturn [Elements::Workbook] The modified workbook.
|
|
943
|
-
# @return [void]
|
|
944
|
-
# @api public
|
|
945
|
-
#: (untyped source, ?untyped target, ?password: String?) ?{ (Elements::Workbook) -> untyped } -> void
|
|
946
|
-
def self.modify(source, target = nil, password: nil)
|
|
947
|
-
raise Error, "source is required" if source.nil?
|
|
948
|
-
raise Error, "block is required" unless block_given?
|
|
949
|
-
|
|
950
|
-
prepared_source = prepare_source_io(source, password)
|
|
951
|
-
in_place = target.nil? || target == source || (source.is_a?(String) && target.is_a?(String) && File.file?(target) && File.identical?(source, target))
|
|
952
|
-
temp_target_path = nil
|
|
953
|
-
|
|
954
|
-
begin
|
|
955
|
-
write_dest = if in_place && source.is_a?(String)
|
|
956
|
-
temp_target = Tempfile.new(["xlsxrb_mod", ".xlsx"], File.dirname(source))
|
|
957
|
-
temp_target_path = temp_target.path
|
|
958
|
-
temp_target.close
|
|
959
|
-
temp_target_path
|
|
960
|
-
elsif in_place && source.is_a?(StringIO)
|
|
961
|
-
StringIO.new
|
|
962
|
-
else
|
|
963
|
-
target || source
|
|
964
|
-
end
|
|
965
|
-
|
|
966
|
-
replaced_entries = {}
|
|
967
|
-
structural_change = false
|
|
968
|
-
|
|
969
|
-
Ooxml::ZipReader.open(prepared_source) do |zip_reader|
|
|
970
|
-
workbook_path = resolve_workbook_entry(zip_reader)
|
|
971
|
-
wb_dir = File.dirname(workbook_path)
|
|
972
|
-
wb_rels_name = wb_dir == "." ? "_rels/#{File.basename(workbook_path)}.rels" : "#{wb_dir}/_rels/#{File.basename(workbook_path)}.rels"
|
|
973
|
-
rels_xml = zip_reader.read_entry(wb_rels_name)
|
|
974
|
-
rels, rel_types = parse_workbook_relationships(rels_xml)
|
|
975
|
-
|
|
976
|
-
sst_entry = resolve_part_entry(zip_reader, rels, "sharedStrings", "sharedStrings.xml", wb_dir)
|
|
977
|
-
shared_strings_xml = sst_entry ? zip_reader.read_entry(sst_entry) : nil
|
|
978
|
-
shared_strings = shared_strings_xml ? Ooxml::SharedStringsParser.parse(shared_strings_xml) : []
|
|
979
|
-
sst_index = {}
|
|
980
|
-
shared_strings.each_with_index { |s, idx| sst_index[s] ||= idx }
|
|
981
|
-
initial_sst_size = shared_strings.size
|
|
982
|
-
|
|
983
|
-
styles_entry = resolve_part_entry(zip_reader, rels, "styles", "styles.xml", wb_dir)
|
|
984
|
-
styles_xml = styles_entry ? zip_reader.read_entry(styles_entry) : nil
|
|
985
|
-
styles = styles_xml ? Ooxml::StylesParser.parse(styles_xml) : {}
|
|
986
|
-
|
|
987
|
-
workbook_xml = zip_reader.read_entry(workbook_path)
|
|
988
|
-
wb_parsed = workbook_xml ? Ooxml::WorkbookParser.parse_with_properties(workbook_xml) : { sheets: [], date1904: false, defined_names: [] }
|
|
989
|
-
workbook_sheets = wb_parsed[:sheets]
|
|
990
|
-
|
|
991
|
-
sheet_entry_map = {}
|
|
992
|
-
ws_idx = 0
|
|
993
|
-
loaded_sheets = workbook_sheets.filter_map do |sheet_info|
|
|
994
|
-
r_id = sheet_info[:r_id]
|
|
995
|
-
target_path = rels[r_id]
|
|
996
|
-
next if non_worksheet_relationship?(rel_types[r_id], target_path)
|
|
997
|
-
|
|
998
|
-
sheet_path = resolve_sheet_entry(zip_reader, target_path, wb_dir, ws_idx)
|
|
999
|
-
ws_idx += 1
|
|
1000
|
-
next unless sheet_path
|
|
1001
|
-
|
|
1002
|
-
sheet_entry_map[sheet_info[:name]] = sheet_path
|
|
1003
|
-
sheet_xml = zip_reader.read_entry(sheet_path) || ""
|
|
1004
|
-
build_worksheet(sheet_info[:name], sheet_xml, shared_strings, styles, state: sheet_info[:state] || :visible, zip_reader: zip_reader, entry_name: sheet_path)
|
|
1005
|
-
end
|
|
1006
|
-
|
|
1007
|
-
mod_unmapped = {}
|
|
1008
|
-
mod_props = {}
|
|
1009
|
-
mod_props[:date1904] = true if wb_parsed[:date1904]
|
|
1010
|
-
mod_props[:active_tab] = wb_parsed[:active_tab] unless wb_parsed[:active_tab].nil?
|
|
1011
|
-
mod_props[:first_sheet] = wb_parsed[:first_sheet] unless wb_parsed[:first_sheet].nil?
|
|
1012
|
-
mod_props[:show_sheet_tabs] = wb_parsed[:show_sheet_tabs] unless wb_parsed[:show_sheet_tabs].nil?
|
|
1013
|
-
mod_props[:tab_ratio] = wb_parsed[:tab_ratio] unless wb_parsed[:tab_ratio].nil?
|
|
1014
|
-
mod_props[:full_calc_on_load] = wb_parsed[:full_calc_on_load] unless wb_parsed[:full_calc_on_load].nil?
|
|
1015
|
-
mod_unmapped[:workbook_properties] = mod_props unless mod_props.empty?
|
|
1016
|
-
|
|
1017
|
-
original_workbook = Elements::Workbook.new(
|
|
1018
|
-
sheets: loaded_sheets,
|
|
1019
|
-
shared_strings: shared_strings,
|
|
1020
|
-
styles: styles,
|
|
1021
|
-
unmapped_data: mod_unmapped,
|
|
1022
|
-
defined_names: wb_parsed[:defined_names] || []
|
|
1023
|
-
)
|
|
1024
|
-
mutable_shared_strings = shared_strings.dup
|
|
1025
|
-
|
|
1026
|
-
result_workbook = yield original_workbook
|
|
1027
|
-
result_workbook = original_workbook unless result_workbook.is_a?(Elements::Workbook)
|
|
1028
|
-
|
|
1029
|
-
structural_change = result_workbook.sheets.size != original_workbook.sheets.size ||
|
|
1030
|
-
result_workbook.sheets.map(&:name) != original_workbook.sheets.map(&:name)
|
|
1031
|
-
|
|
1032
|
-
if structural_change
|
|
1033
|
-
write_target = target || source
|
|
1034
|
-
write(write_target, result_workbook, password: password)
|
|
1035
|
-
else
|
|
1036
|
-
result_workbook.sheets.each_with_index do |new_sheet, idx|
|
|
1037
|
-
orig_sheet = original_workbook.sheets[idx]
|
|
1038
|
-
next if new_sheet.equal?(orig_sheet) || new_sheet == orig_sheet
|
|
1039
|
-
|
|
1040
|
-
entry_name = sheet_entry_map[new_sheet.name] || "xl/worksheets/sheet#{idx + 1}.xml"
|
|
1041
|
-
orig_sheet_xml = zip_reader.read_entry(entry_name) || ""
|
|
1042
|
-
|
|
1043
|
-
new_sheet_data = serialize_sheet_data_xml(
|
|
1044
|
-
new_sheet.rows,
|
|
1045
|
-
mutable_shared_strings,
|
|
1046
|
-
sst_index,
|
|
1047
|
-
use_sst: !shared_strings_xml.nil?
|
|
1048
|
-
)
|
|
1049
|
-
updated_sheet_xml = replace_sheet_data(orig_sheet_xml, new_sheet_data)
|
|
1050
|
-
updated_sheet_xml = update_dimension(updated_sheet_xml, new_sheet.rows)
|
|
1051
|
-
|
|
1052
|
-
all_hyperlinks = new_sheet.hyperlinks.dup
|
|
1053
|
-
new_sheet.rows.each do |row|
|
|
1054
|
-
row.cells.each do |cell|
|
|
1055
|
-
all_hyperlinks[cell.ref] ||= cell.hyperlink if cell.hyperlink
|
|
1056
|
-
end
|
|
1057
|
-
end
|
|
1058
|
-
|
|
1059
|
-
if all_hyperlinks != orig_sheet.hyperlinks
|
|
1060
|
-
rels_path = entry_name.sub(%r{([^/]+)$}, '_rels/\1.rels')
|
|
1061
|
-
orig_rels_xml = replaced_entries[rels_path] || zip_reader.read_entry(rels_path)
|
|
1062
|
-
updated_sheet_xml, updated_rels_xml = update_sheet_hyperlinks(
|
|
1063
|
-
updated_sheet_xml,
|
|
1064
|
-
orig_rels_xml,
|
|
1065
|
-
all_hyperlinks
|
|
1066
|
-
)
|
|
1067
|
-
replaced_entries[rels_path] = updated_rels_xml if updated_rels_xml
|
|
1068
|
-
end
|
|
1069
|
-
|
|
1070
|
-
all_comments = new_sheet.comments.dup
|
|
1071
|
-
new_sheet.rows.each do |row|
|
|
1072
|
-
row.cells.each do |cell|
|
|
1073
|
-
if cell.comment && all_comments.none? { |c| (c[:ref] || c[:cell])&.to_s&.upcase == cell.ref.upcase }
|
|
1074
|
-
entry = cell.comment.is_a?(Hash) ? cell.comment.merge(ref: cell.ref) : { ref: cell.ref, text: cell.comment }
|
|
1075
|
-
all_comments << entry
|
|
1076
|
-
end
|
|
1077
|
-
end
|
|
1078
|
-
end
|
|
1079
|
-
|
|
1080
|
-
if all_comments != orig_sheet.comments
|
|
1081
|
-
rels_path = entry_name.sub(%r{([^/]+)$}, '_rels/\1.rels')
|
|
1082
|
-
orig_rels_xml = replaced_entries[rels_path] || zip_reader.read_entry(rels_path)
|
|
1083
|
-
updated_sheet_xml, updated_rels_xml = update_sheet_comments(
|
|
1084
|
-
updated_sheet_xml,
|
|
1085
|
-
rels_path,
|
|
1086
|
-
orig_rels_xml,
|
|
1087
|
-
all_comments,
|
|
1088
|
-
zip_reader,
|
|
1089
|
-
idx,
|
|
1090
|
-
entry_name,
|
|
1091
|
-
replaced_entries
|
|
1092
|
-
)
|
|
1093
|
-
replaced_entries[rels_path] = updated_rels_xml if updated_rels_xml
|
|
1094
|
-
end
|
|
1095
|
-
|
|
1096
|
-
replaced_entries[entry_name] = updated_sheet_xml
|
|
1097
|
-
end
|
|
1098
|
-
|
|
1099
|
-
if mutable_shared_strings.size > initial_sst_size && shared_strings_xml
|
|
1100
|
-
new_strings = mutable_shared_strings[initial_sst_size..]
|
|
1101
|
-
sst_path = sst_entry || (wb_dir == "." ? "sharedStrings.xml" : "#{wb_dir}/sharedStrings.xml")
|
|
1102
|
-
replaced_entries[sst_path] = append_to_shared_strings_xml(
|
|
1103
|
-
shared_strings_xml,
|
|
1104
|
-
new_strings
|
|
1105
|
-
)
|
|
1106
|
-
end
|
|
1107
|
-
|
|
1108
|
-
perform_modify_write(
|
|
1109
|
-
write_dest,
|
|
1110
|
-
zip_reader,
|
|
1111
|
-
replaced_entries,
|
|
1112
|
-
password: password
|
|
1113
|
-
)
|
|
1114
|
-
end
|
|
1115
|
-
end
|
|
1116
|
-
|
|
1117
|
-
if in_place && !structural_change
|
|
1118
|
-
if source.is_a?(String) && temp_target_path
|
|
1119
|
-
FileUtils.mv(temp_target_path, source)
|
|
1120
|
-
temp_target_path = nil
|
|
1121
|
-
elsif source.is_a?(StringIO) && write_dest.is_a?(StringIO)
|
|
1122
|
-
source.string = write_dest.string
|
|
1123
|
-
elsif source.respond_to?(:write) && source.respond_to?(:seek) && write_dest.is_a?(StringIO)
|
|
1124
|
-
source.seek(0)
|
|
1125
|
-
source.write(write_dest.string)
|
|
1126
|
-
source.truncate(source.pos) if source.respond_to?(:truncate)
|
|
1127
|
-
source.rewind
|
|
1128
|
-
end
|
|
1129
|
-
end
|
|
1130
|
-
ensure
|
|
1131
|
-
if temp_target_path && File.exist?(temp_target_path)
|
|
1132
|
-
begin
|
|
1133
|
-
File.unlink(temp_target_path)
|
|
1134
|
-
rescue SystemCallError
|
|
1135
|
-
nil
|
|
1136
|
-
end
|
|
1137
|
-
end
|
|
1138
|
-
end
|
|
1139
|
-
end
|
|
1140
|
-
|
|
1141
1251
|
# Builds an in-memory {Elements::Workbook} using a declarative DSL.
|
|
1142
1252
|
#
|
|
1143
1253
|
# @example Build an in-memory workbook
|
|
@@ -1149,6 +1259,7 @@ module Xlsxrb
|
|
|
1149
1259
|
# end
|
|
1150
1260
|
#
|
|
1151
1261
|
# @param strict_excel_mode [Boolean] Whether to enforce Microsoft Excel specification limits.
|
|
1262
|
+
# @param default_font [Hash, nil] Optional default font options.
|
|
1152
1263
|
# @yield [builder]
|
|
1153
1264
|
# @yieldparam builder [Xlsxrb::WorkbookBuilder]
|
|
1154
1265
|
# @return [Elements::Workbook] The compiled in-memory workbook.
|
|
@@ -1178,7 +1289,8 @@ module Xlsxrb
|
|
|
1178
1289
|
return "xl/workbook.xml" if zip_reader.entry?("xl/workbook.xml")
|
|
1179
1290
|
return "workbook.xml" if zip_reader.entry?("workbook.xml")
|
|
1180
1291
|
|
|
1181
|
-
|
|
1292
|
+
# A ZIP archive without a workbook part, such as an OpenDocument spreadsheet (.ods) renamed to .xlsx.
|
|
1293
|
+
raise ParseError, "not an XLSX workbook: the ZIP archive has no workbook part (xl/workbook.xml)"
|
|
1182
1294
|
end
|
|
1183
1295
|
|
|
1184
1296
|
def parse_workbook_relationships(rels_xml)
|
|
@@ -1243,20 +1355,28 @@ module Xlsxrb
|
|
|
1243
1355
|
fallbacks.find { |f| zip_reader.entry?(f) }
|
|
1244
1356
|
end
|
|
1245
1357
|
|
|
1246
|
-
#: (String name, String? sheet_xml, Array[String] shared_strings, untyped styles, ?state: Symbol, ?zip_reader: Ooxml::ZipReader?, ?entry_name: String?, ?hyperlinks: Hash[String, untyped]?, ?comments: Array[Hash[Symbol, untyped]]?, ?images: Array[Elements::Image]?, ?date1904: bool, ?dimension: String?, ?trim_empty_rows: bool, ?pad_empty_rows: bool, ?pad_empty_cells: bool, ?merged_cells: Array[String]?, ?auto_filter: String?, ?tables: Array[Hash[Symbol, untyped]]?, ?shapes: Array[Hash[Symbol, untyped]]?, ?freeze_pane: Hash[Symbol, untyped]?, ?page_setup: Hash[Symbol, untyped]?, ?page_margins: Hash[Symbol, untyped]?, ?header_footer: Hash[Symbol, untyped]?, ?print_options: Hash[Symbol, untyped]?, ?sheet_protection: Hash[Symbol, untyped]?, ?sheet_view: Hash[Symbol, untyped]?, ?sheet_properties: Hash[Symbol, untyped]?, ?sheet_format: Hash[Symbol, untyped]?, ?row_breaks: Array[untyped]?, ?col_breaks: Array[untyped]?, ?protected_ranges: Array[Hash[Symbol, untyped]]?, ?cell_watches: Array[String]?, ?ignored_errors: Array[Hash[Symbol, untyped]]?, ?phonetic_properties: Hash[Symbol, untyped]?, ?selection: (Hash[Symbol, untyped] | Array[Hash[Symbol, untyped]])?, ?
|
|
1247
|
-
def build_worksheet(name, sheet_xml, shared_strings, styles, state: :visible, zip_reader: nil, entry_name: nil, hyperlinks: nil, comments: nil, images: nil, date1904: false, dimension: nil, trim_empty_rows: false, pad_empty_rows: false, pad_empty_cells: false, merged_cells: nil, auto_filter: nil, tables: nil, shapes: nil, freeze_pane: nil, page_setup: nil, page_margins: nil, header_footer: nil, print_options: nil, sheet_protection: nil, sheet_view: nil, sheet_properties: nil, sheet_format: nil, row_breaks: nil,
|
|
1358
|
+
#: (String name, String? sheet_xml, Array[String] shared_strings, untyped styles, ?state: Symbol, ?zip_reader: Ooxml::ZipReader?, ?entry_name: String?, ?hyperlinks: Hash[String, untyped]?, ?comments: Array[Hash[Symbol, untyped]]?, ?images: Array[Elements::Image]?, ?date1904: bool, ?dimension: String?, ?trim_empty_rows: bool, ?pad_empty_rows: bool, ?pad_empty_cells: bool, ?merged_cells: Array[String]?, ?auto_filter: String?, ?tables: Array[Hash[Symbol, untyped]]?, ?shapes: Array[Hash[Symbol, untyped]]?, ?freeze_pane: Hash[Symbol, untyped]?, ?page_setup: Hash[Symbol, untyped]?, ?page_margins: Hash[Symbol, untyped]?, ?header_footer: Hash[Symbol, untyped]?, ?print_options: Hash[Symbol, untyped]?, ?sheet_protection: Hash[Symbol, untyped]?, ?sheet_view: Hash[Symbol, untyped]?, ?sheet_properties: Hash[Symbol, untyped]?, ?sheet_format: Hash[Symbol, untyped]?, ?row_breaks: Array[untyped]?, ?column_breaks: Array[untyped]?, ?col_breaks: Array[untyped]?, ?protected_ranges: Array[Hash[Symbol, untyped]]?, ?cell_watches: Array[String]?, ?ignored_errors: Array[Hash[Symbol, untyped]]?, ?phonetic_properties: Hash[Symbol, untyped]?, ?selection: (Hash[Symbol, untyped] | Array[Hash[Symbol, untyped]])?, ?sheet_calc_properties: Hash[Symbol, untyped]?, ?background_image: Hash[Symbol, untyped]?, ?threaded_comments: Array[Hash[Symbol, untyped]]?, ?columns: Array[Elements::Column]?, ?pivot_tables: Array[Hash[Symbol, untyped]]?, ?split_pane: Hash[Symbol, untyped]?, ?filter_columns: Hash[Integer, Hash[Symbol, untyped]]?, ?sort_state: Hash[Symbol, untyped]?, ?header_footer_images: (Array[Elements::HeaderFooterImage] | Array[Hash[Symbol, untyped]])?, ?charts: (Array[Elements::Chart] | Array[Hash[Symbol, untyped]])?, ?sparkline_groups: (Array[Elements::SparklineGroup] | Array[Hash[Symbol, untyped]])?, ?print_area: String?, ?print_titles: (Elements::PrintTitles | Hash[Symbol, untyped])?) -> Elements::Worksheet
|
|
1359
|
+
def build_worksheet(name, sheet_xml, shared_strings, styles, state: :visible, zip_reader: nil, entry_name: nil, hyperlinks: nil, comments: nil, images: nil, date1904: false, dimension: nil, trim_empty_rows: false, pad_empty_rows: false, pad_empty_cells: false, merged_cells: nil, auto_filter: nil, tables: nil, shapes: nil, freeze_pane: nil, page_setup: nil, page_margins: nil, header_footer: nil, print_options: nil, sheet_protection: nil, sheet_view: nil, sheet_properties: nil, sheet_format: nil, row_breaks: nil, column_breaks: nil, protected_ranges: nil, cell_watches: nil, ignored_errors: nil, phonetic_properties: nil, selection: nil, sheet_calc_properties: nil, background_image: nil, threaded_comments: nil, columns: nil, pivot_tables: nil, split_pane: nil, filter_columns: nil, sort_state: nil, header_footer_images: nil, charts: nil, sparkline_groups: nil, print_area: nil, print_titles: nil)
|
|
1248
1360
|
sheet_dimension = dimension || sheet_xml&.slice(/<(?:[a-zA-Z0-9_]+:)?dimension\b[^>]*\bref=["']([^"']+)["']/, 1)
|
|
1249
1361
|
if sheet_xml.nil? || sheet_xml.empty?
|
|
1250
1362
|
return Elements::Worksheet.new(
|
|
1251
1363
|
name: name, state: state, styles: styles, images: images || [], date1904: date1904,
|
|
1252
1364
|
dimension: sheet_dimension, trim_empty_rows: trim_empty_rows, pad_empty_rows: pad_empty_rows, pad_empty_cells: pad_empty_cells,
|
|
1365
|
+
columns: columns || [],
|
|
1366
|
+
charts: charts || [],
|
|
1367
|
+
sparkline_groups: sparkline_groups || [],
|
|
1368
|
+
print_area: print_area,
|
|
1369
|
+
print_titles: print_titles,
|
|
1253
1370
|
merged_cells: merged_cells || [], auto_filter: auto_filter,
|
|
1254
1371
|
tables: tables || [], shapes: shapes || [], freeze_pane: freeze_pane,
|
|
1372
|
+
split_pane: split_pane, pivot_tables: pivot_tables || [],
|
|
1373
|
+
filter_columns: filter_columns || {}, sort_state: sort_state,
|
|
1374
|
+
header_footer_images: header_footer_images || [],
|
|
1255
1375
|
page_setup: page_setup || {}, page_margins: page_margins, header_footer: header_footer || {},
|
|
1256
1376
|
print_options: print_options || {}, sheet_protection: sheet_protection, sheet_view: sheet_view || {},
|
|
1257
|
-
sheet_properties: sheet_properties || {}, sheet_format: sheet_format || {}, row_breaks: row_breaks || [],
|
|
1377
|
+
sheet_properties: sheet_properties || {}, sheet_format: sheet_format || {}, row_breaks: row_breaks || [], column_breaks: column_breaks || [],
|
|
1258
1378
|
protected_ranges: protected_ranges || [], cell_watches: cell_watches || [], ignored_errors: ignored_errors || [],
|
|
1259
|
-
phonetic_properties: phonetic_properties, selection: selection,
|
|
1379
|
+
phonetic_properties: phonetic_properties, selection: selection, sheet_calc_properties: sheet_calc_properties,
|
|
1260
1380
|
background_image: background_image,
|
|
1261
1381
|
threaded_comments: threaded_comments || []
|
|
1262
1382
|
)
|
|
@@ -1270,7 +1390,7 @@ module Xlsxrb
|
|
|
1270
1390
|
raw_columns = Ooxml::WorksheetParser.parse_columns(sheet_xml)
|
|
1271
1391
|
|
|
1272
1392
|
rows = raw_rows.map { |rr| build_row_from_raw(rr, sheet_hyperlinks, sheet_comments, styles, date1904: date1904, threaded_comments: sheet_threaded_comments) }
|
|
1273
|
-
|
|
1393
|
+
sheet_columns = columns || raw_columns.map do |rc|
|
|
1274
1394
|
# Columns from OOXML are 1-based min/max ranges; convert to 0-based
|
|
1275
1395
|
col_unmapped = {}
|
|
1276
1396
|
col_unmapped[:style_index] = rc[:style_index] if rc[:style_index]
|
|
@@ -1311,16 +1431,27 @@ module Xlsxrb
|
|
|
1311
1431
|
[]
|
|
1312
1432
|
end
|
|
1313
1433
|
|
|
1314
|
-
sheet_auto_filter = auto_filter
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1434
|
+
sheet_auto_filter = auto_filter
|
|
1435
|
+
sheet_filter_columns = filter_columns
|
|
1436
|
+
if sheet_auto_filter.nil? && sheet_xml.include?("<autoFilter")
|
|
1437
|
+
af_listener = Ooxml::Reader::AutoFilterListener.new
|
|
1438
|
+
Ooxml::XmlParser.parse(sheet_xml, af_listener)
|
|
1439
|
+
sheet_auto_filter = af_listener.ref
|
|
1440
|
+
sheet_filter_columns ||= af_listener.filter_columns
|
|
1441
|
+
end
|
|
1442
|
+
sheet_filter_columns ||= {}
|
|
1443
|
+
|
|
1444
|
+
sheet_sort_state = sort_state || if sheet_xml.include?("<sortState")
|
|
1445
|
+
ss_listener = Ooxml::Reader::SortStateListener.new
|
|
1446
|
+
Ooxml::XmlParser.parse(sheet_xml, ss_listener)
|
|
1447
|
+
ss_listener.sort_state
|
|
1448
|
+
end
|
|
1319
1449
|
|
|
1320
1450
|
sheet_tables = tables || resolve_tables(zip_reader: zip_reader, entry_name: entry_name)
|
|
1451
|
+
sheet_pivot_tables = pivot_tables || resolve_pivot_tables(zip_reader: zip_reader, entry_name: entry_name)
|
|
1321
1452
|
sheet_shapes = shapes || resolve_shapes(zip_reader: zip_reader, entry_name: entry_name)
|
|
1322
1453
|
|
|
1323
|
-
sheet_view_data = if freeze_pane.nil? || sheet_view.nil? || selection.nil?
|
|
1454
|
+
sheet_view_data = if freeze_pane.nil? || split_pane.nil? || sheet_view.nil? || selection.nil?
|
|
1324
1455
|
if sheet_xml.include?("<sheetView")
|
|
1325
1456
|
v_listener = Ooxml::Reader::SheetViewListener.new
|
|
1326
1457
|
Ooxml::XmlParser.parse(sheet_xml, v_listener)
|
|
@@ -1329,9 +1460,10 @@ module Xlsxrb
|
|
|
1329
1460
|
{ view: {}, pane: nil, selection: nil }
|
|
1330
1461
|
end
|
|
1331
1462
|
else
|
|
1332
|
-
{ view: sheet_view, pane: freeze_pane, selection: selection }
|
|
1463
|
+
{ view: sheet_view, pane: freeze_pane || split_pane, selection: selection }
|
|
1333
1464
|
end
|
|
1334
|
-
sheet_freeze_pane = freeze_pane || sheet_view_data[:pane]
|
|
1465
|
+
sheet_freeze_pane = freeze_pane || (sheet_view_data[:pane] if sheet_view_data[:pane] && sheet_view_data[:pane][:state] == :frozen)
|
|
1466
|
+
sheet_split_pane = split_pane || (sheet_view_data[:pane] if sheet_view_data[:pane] && sheet_view_data[:pane][:state] != :frozen)
|
|
1335
1467
|
sheet_view_val = sheet_view || sheet_view_data[:view] || {}
|
|
1336
1468
|
sheet_selection = selection || sheet_view_data[:selection]
|
|
1337
1469
|
|
|
@@ -1357,7 +1489,7 @@ module Xlsxrb
|
|
|
1357
1489
|
{}
|
|
1358
1490
|
end
|
|
1359
1491
|
|
|
1360
|
-
print_data = if page_setup.nil? || page_margins.nil? || header_footer.nil? || print_options.nil? || row_breaks.nil? ||
|
|
1492
|
+
print_data = if page_setup.nil? || page_margins.nil? || header_footer.nil? || print_options.nil? || row_breaks.nil? || column_breaks.nil?
|
|
1361
1493
|
if sheet_xml.match?(/<(?:pageSetup|pageMargins|headerFooter|printOptions|rowBreaks|colBreaks)\b/)
|
|
1362
1494
|
pg_listener = Ooxml::Reader::PrintPageListener.new
|
|
1363
1495
|
Ooxml::XmlParser.parse(sheet_xml, pg_listener)
|
|
@@ -1367,13 +1499,13 @@ module Xlsxrb
|
|
|
1367
1499
|
header_footer: pg_listener.header_footer,
|
|
1368
1500
|
print_options: pg_listener.print_options,
|
|
1369
1501
|
row_breaks: pg_listener.row_breaks,
|
|
1370
|
-
|
|
1502
|
+
column_breaks: pg_listener.column_breaks
|
|
1371
1503
|
}
|
|
1372
1504
|
else
|
|
1373
|
-
{ page_margins: nil, page_setup: {}, header_footer: {}, print_options: {}, row_breaks: [],
|
|
1505
|
+
{ page_margins: nil, page_setup: {}, header_footer: {}, print_options: {}, row_breaks: [], column_breaks: [] }
|
|
1374
1506
|
end
|
|
1375
1507
|
else
|
|
1376
|
-
{ page_margins: page_margins, page_setup: page_setup, header_footer: header_footer, print_options: print_options, row_breaks: row_breaks,
|
|
1508
|
+
{ page_margins: page_margins, page_setup: page_setup, header_footer: header_footer, print_options: print_options, row_breaks: row_breaks, column_breaks: column_breaks }
|
|
1377
1509
|
end
|
|
1378
1510
|
|
|
1379
1511
|
sheet_prot_ranges = protected_ranges || if sheet_xml.include?("<protectedRanges")
|
|
@@ -1406,11 +1538,19 @@ module Xlsxrb
|
|
|
1406
1538
|
pp_listener.phonetic_pr
|
|
1407
1539
|
end
|
|
1408
1540
|
|
|
1541
|
+
sheet_charts = charts || resolve_charts(zip_reader: zip_reader, entry_name: entry_name)
|
|
1542
|
+
sheet_sparkline_groups = sparkline_groups || (sheet_xml.include?("sparklineGroup") ? resolve_sparkline_groups(sheet_xml) : [])
|
|
1543
|
+
sheet_hf_images = header_footer_images || (sheet_xml.include?("legacyDrawingHF") ? resolve_header_footer_images(sheet_xml, zip_reader: zip_reader, entry_name: entry_name) : [])
|
|
1544
|
+
|
|
1409
1545
|
Elements::Worksheet.new(
|
|
1410
1546
|
name: name,
|
|
1411
1547
|
rows: rows,
|
|
1412
|
-
columns:
|
|
1413
|
-
|
|
1548
|
+
columns: sheet_columns,
|
|
1549
|
+
charts: sheet_charts,
|
|
1550
|
+
sparkline_groups: sheet_sparkline_groups,
|
|
1551
|
+
print_area: print_area,
|
|
1552
|
+
print_titles: print_titles,
|
|
1553
|
+
conditional_formats: cfs,
|
|
1414
1554
|
data_validations: dvs,
|
|
1415
1555
|
state: state,
|
|
1416
1556
|
hyperlinks: sheet_hyperlinks,
|
|
@@ -1425,8 +1565,13 @@ module Xlsxrb
|
|
|
1425
1565
|
merged_cells: sheet_merged_cells,
|
|
1426
1566
|
auto_filter: sheet_auto_filter,
|
|
1427
1567
|
tables: sheet_tables,
|
|
1568
|
+
pivot_tables: sheet_pivot_tables,
|
|
1428
1569
|
shapes: sheet_shapes,
|
|
1429
1570
|
freeze_pane: sheet_freeze_pane,
|
|
1571
|
+
split_pane: sheet_split_pane,
|
|
1572
|
+
filter_columns: sheet_filter_columns,
|
|
1573
|
+
sort_state: sheet_sort_state,
|
|
1574
|
+
header_footer_images: sheet_hf_images,
|
|
1430
1575
|
page_setup: page_setup || print_data[:page_setup] || {},
|
|
1431
1576
|
page_margins: page_margins || print_data[:page_margins],
|
|
1432
1577
|
header_footer: header_footer || print_data[:header_footer] || {},
|
|
@@ -1436,13 +1581,13 @@ module Xlsxrb
|
|
|
1436
1581
|
sheet_properties: sheet_props,
|
|
1437
1582
|
sheet_format: sheet_fmt,
|
|
1438
1583
|
row_breaks: row_breaks || print_data[:row_breaks] || [],
|
|
1439
|
-
|
|
1584
|
+
column_breaks: column_breaks || print_data[:column_breaks] || [],
|
|
1440
1585
|
protected_ranges: sheet_prot_ranges,
|
|
1441
1586
|
cell_watches: sheet_watches,
|
|
1442
1587
|
ignored_errors: sheet_ignored_errors,
|
|
1443
1588
|
phonetic_properties: sheet_phonetic,
|
|
1444
1589
|
selection: sheet_selection,
|
|
1445
|
-
|
|
1590
|
+
sheet_calc_properties: sheet_calc_properties,
|
|
1446
1591
|
background_image: background_image || (sheet_xml.include?("<picture") ? resolve_background_image(sheet_xml, zip_reader: zip_reader, entry_name: entry_name) : nil),
|
|
1447
1592
|
threaded_comments: sheet_threaded_comments
|
|
1448
1593
|
)
|
|
@@ -1474,7 +1619,14 @@ module Xlsxrb
|
|
|
1474
1619
|
entry[:display] = link[:display] if link[:display]
|
|
1475
1620
|
entry[:tooltip] = link[:tooltip] if link[:tooltip]
|
|
1476
1621
|
entry[:location] = link[:location] if link[:location]
|
|
1477
|
-
|
|
1622
|
+
next if entry.empty?
|
|
1623
|
+
|
|
1624
|
+
result[link[:ref]] = Elements::Hyperlink.new(
|
|
1625
|
+
url: entry[:url],
|
|
1626
|
+
location: entry[:location],
|
|
1627
|
+
tooltip: entry[:tooltip],
|
|
1628
|
+
display: entry[:display]
|
|
1629
|
+
)
|
|
1478
1630
|
end
|
|
1479
1631
|
result
|
|
1480
1632
|
end
|
|
@@ -1501,7 +1653,7 @@ module Xlsxrb
|
|
|
1501
1653
|
rels_xml = zip_reader.read_entry(rels_path)
|
|
1502
1654
|
return [] if rels_xml.nil? || rels_xml.empty?
|
|
1503
1655
|
|
|
1504
|
-
parser =
|
|
1656
|
+
parser = Ooxml::XmlParser.sax2_parser(rels_xml)
|
|
1505
1657
|
listener = Ooxml::Reader::RelsListener.new
|
|
1506
1658
|
parser.listen(listener)
|
|
1507
1659
|
parser.parse
|
|
@@ -1515,11 +1667,47 @@ module Xlsxrb
|
|
|
1515
1667
|
xml = zip_reader.read_entry(comments_path)
|
|
1516
1668
|
return [] if xml.nil? || xml.empty?
|
|
1517
1669
|
|
|
1518
|
-
c_parser =
|
|
1670
|
+
c_parser = Ooxml::XmlParser.sax2_parser(xml)
|
|
1519
1671
|
c_listener = Ooxml::Reader::CommentsListener.new
|
|
1520
1672
|
c_parser.listen(c_listener)
|
|
1521
1673
|
c_parser.parse
|
|
1522
|
-
c_listener.comments
|
|
1674
|
+
comments = c_listener.comments
|
|
1675
|
+
notes = vml_notes(zip_reader, listener.relationships, base_dir)
|
|
1676
|
+
unless notes.empty?
|
|
1677
|
+
comments.each do |c|
|
|
1678
|
+
note = notes[c[:ref].to_s.upcase]
|
|
1679
|
+
next unless note
|
|
1680
|
+
|
|
1681
|
+
c[:visible] = true if note[:visible]
|
|
1682
|
+
c[:anchor] = note[:anchor] if note[:anchor]
|
|
1683
|
+
end
|
|
1684
|
+
end
|
|
1685
|
+
comments
|
|
1686
|
+
end
|
|
1687
|
+
|
|
1688
|
+
# Reads the comment notes of the sheet's legacy VML drawing, keyed by cell reference:
|
|
1689
|
+
# whether each is shown permanently (<x:Visible/>) and its <x:Anchor> box position.
|
|
1690
|
+
#: (Ooxml::ZipReader zip_reader, Array[Hash[Symbol, untyped]] relationships, String base_dir) -> Hash[String, Hash[Symbol, untyped]]
|
|
1691
|
+
def vml_notes(zip_reader, relationships, base_dir)
|
|
1692
|
+
rel = relationships.find { |r| r[:type]&.end_with?("/vmlDrawing") }
|
|
1693
|
+
vml = rel && zip_reader.read_entry(resolve_relative_path(base_dir, rel[:target]))
|
|
1694
|
+
return {} if vml.nil?
|
|
1695
|
+
|
|
1696
|
+
vml.split("</v:shape>").each_with_object({}) do |shape, notes|
|
|
1697
|
+
next unless shape.include?('ObjectType="Note"')
|
|
1698
|
+
|
|
1699
|
+
row = shape[%r{<x:Row>\s*(\d+)\s*</x:Row>}, 1]
|
|
1700
|
+
col = shape[%r{<x:Column>\s*(\d+)\s*</x:Column>}, 1]
|
|
1701
|
+
next unless row && col
|
|
1702
|
+
|
|
1703
|
+
anchor = shape[%r{<x:Anchor>([\d,\s]+)</x:Anchor>}, 1]&.split(",")&.map(&:to_i)
|
|
1704
|
+
# The writer's default box reads back as no anchor, as it was built.
|
|
1705
|
+
anchor = nil if anchor&.size != 8 || anchor == Elements::Comment.default_anchor(col.to_i, row.to_i)
|
|
1706
|
+
notes["#{Elements::Cell._column_letter(col.to_i)}#{row.to_i + 1}"] = {
|
|
1707
|
+
visible: shape.include?("<x:Visible"),
|
|
1708
|
+
anchor: anchor
|
|
1709
|
+
}
|
|
1710
|
+
end
|
|
1523
1711
|
end
|
|
1524
1712
|
|
|
1525
1713
|
#: (?zip_reader: Ooxml::ZipReader?, ?entry_name: String?) -> Array[Hash[Symbol, untyped]]
|
|
@@ -1530,7 +1718,7 @@ module Xlsxrb
|
|
|
1530
1718
|
rels_xml = zip_reader.read_entry(rels_path)
|
|
1531
1719
|
return [] if rels_xml.nil? || rels_xml.empty?
|
|
1532
1720
|
|
|
1533
|
-
parser =
|
|
1721
|
+
parser = Ooxml::XmlParser.sax2_parser(rels_xml)
|
|
1534
1722
|
listener = Ooxml::Reader::RelsListener.new
|
|
1535
1723
|
parser.listen(listener)
|
|
1536
1724
|
parser.parse
|
|
@@ -1544,7 +1732,7 @@ module Xlsxrb
|
|
|
1544
1732
|
xml = zip_reader.read_entry(tc_path)
|
|
1545
1733
|
return [] if xml.nil? || xml.empty?
|
|
1546
1734
|
|
|
1547
|
-
tc_parser =
|
|
1735
|
+
tc_parser = Ooxml::XmlParser.sax2_parser(xml)
|
|
1548
1736
|
tc_listener = Ooxml::Reader::ThreadedCommentsListener.new
|
|
1549
1737
|
tc_parser.listen(tc_listener)
|
|
1550
1738
|
tc_parser.parse
|
|
@@ -1565,7 +1753,7 @@ module Xlsxrb
|
|
|
1565
1753
|
if xml.nil? || xml.empty?
|
|
1566
1754
|
wb_rels_xml = zip_reader.read_entry("xl/_rels/workbook.xml.rels")
|
|
1567
1755
|
if wb_rels_xml && !wb_rels_xml.empty?
|
|
1568
|
-
parser =
|
|
1756
|
+
parser = Ooxml::XmlParser.sax2_parser(wb_rels_xml)
|
|
1569
1757
|
listener = Ooxml::Reader::RelsListener.new
|
|
1570
1758
|
parser.listen(listener)
|
|
1571
1759
|
parser.parse
|
|
@@ -1578,7 +1766,7 @@ module Xlsxrb
|
|
|
1578
1766
|
end
|
|
1579
1767
|
return {} if xml.nil? || xml.empty?
|
|
1580
1768
|
|
|
1581
|
-
p_parser =
|
|
1769
|
+
p_parser = Ooxml::XmlParser.sax2_parser(xml)
|
|
1582
1770
|
p_listener = Ooxml::Reader::PersonListListener.new
|
|
1583
1771
|
p_parser.listen(p_listener)
|
|
1584
1772
|
p_parser.parse
|
|
@@ -1593,7 +1781,7 @@ module Xlsxrb
|
|
|
1593
1781
|
rels_xml = zip_reader.read_entry(rels_path)
|
|
1594
1782
|
return [] if rels_xml.nil? || rels_xml.empty?
|
|
1595
1783
|
|
|
1596
|
-
parser =
|
|
1784
|
+
parser = Ooxml::XmlParser.sax2_parser(rels_xml)
|
|
1597
1785
|
listener = Ooxml::Reader::RelsListener.new
|
|
1598
1786
|
parser.listen(listener)
|
|
1599
1787
|
parser.parse
|
|
@@ -1611,7 +1799,7 @@ module Xlsxrb
|
|
|
1611
1799
|
drawing_rels_xml = zip_reader.read_entry(drawing_rels_path)
|
|
1612
1800
|
drawing_rels = {}
|
|
1613
1801
|
if drawing_rels_xml && !drawing_rels_xml.empty?
|
|
1614
|
-
d_parser =
|
|
1802
|
+
d_parser = Ooxml::XmlParser.sax2_parser(drawing_rels_xml)
|
|
1615
1803
|
d_listener = Ooxml::Reader::RelsListener.new
|
|
1616
1804
|
d_parser.listen(d_listener)
|
|
1617
1805
|
d_parser.parse
|
|
@@ -1620,7 +1808,7 @@ module Xlsxrb
|
|
|
1620
1808
|
end
|
|
1621
1809
|
end
|
|
1622
1810
|
|
|
1623
|
-
p_parser =
|
|
1811
|
+
p_parser = Ooxml::XmlParser.sax2_parser(drawing_xml)
|
|
1624
1812
|
img_listener = Ooxml::Reader::DrawingImagesListener.new
|
|
1625
1813
|
p_parser.listen(img_listener)
|
|
1626
1814
|
p_parser.parse
|
|
@@ -1637,9 +1825,9 @@ module Xlsxrb
|
|
|
1637
1825
|
img_data = zip_reader.read_entry(media_path)
|
|
1638
1826
|
end
|
|
1639
1827
|
|
|
1640
|
-
from_col = raw_img[:from_col] || 0
|
|
1828
|
+
from_col = raw_img[:from_column] || raw_img[:from_col] || 0
|
|
1641
1829
|
from_row = raw_img[:from_row] || 0
|
|
1642
|
-
to_col = raw_img[:to_col]
|
|
1830
|
+
to_col = raw_img[:to_column] || raw_img[:to_col]
|
|
1643
1831
|
to_row = raw_img[:to_row]
|
|
1644
1832
|
cx = raw_img[:cx]
|
|
1645
1833
|
cy = raw_img[:cy]
|
|
@@ -1649,9 +1837,9 @@ module Xlsxrb
|
|
|
1649
1837
|
filename: filename || "image.png",
|
|
1650
1838
|
name: name,
|
|
1651
1839
|
data: img_data,
|
|
1652
|
-
|
|
1840
|
+
from_column: from_col,
|
|
1653
1841
|
from_row: from_row,
|
|
1654
|
-
|
|
1842
|
+
to_column: to_col,
|
|
1655
1843
|
to_row: to_row,
|
|
1656
1844
|
cx: cx,
|
|
1657
1845
|
cy: cy,
|
|
@@ -1673,7 +1861,7 @@ module Xlsxrb
|
|
|
1673
1861
|
rels_xml = zip_reader.read_entry(rels_path)
|
|
1674
1862
|
return nil if rels_xml.nil? || rels_xml.empty?
|
|
1675
1863
|
|
|
1676
|
-
parser =
|
|
1864
|
+
parser = Ooxml::XmlParser.sax2_parser(rels_xml)
|
|
1677
1865
|
listener = Ooxml::Reader::RelsListener.new
|
|
1678
1866
|
parser.listen(listener)
|
|
1679
1867
|
parser.parse
|
|
@@ -1698,10 +1886,10 @@ module Xlsxrb
|
|
|
1698
1886
|
end
|
|
1699
1887
|
|
|
1700
1888
|
{
|
|
1889
|
+
r_id: picture_rid,
|
|
1890
|
+
path: target_path,
|
|
1891
|
+
extension: ext,
|
|
1701
1892
|
data: data.b,
|
|
1702
|
-
file_data: data.b,
|
|
1703
|
-
ext: ext,
|
|
1704
|
-
filename: File.basename(target_path),
|
|
1705
1893
|
content_type: mime
|
|
1706
1894
|
}.freeze
|
|
1707
1895
|
end
|
|
@@ -1714,7 +1902,7 @@ module Xlsxrb
|
|
|
1714
1902
|
rels_xml = zip_reader.read_entry(rels_path)
|
|
1715
1903
|
return [] if rels_xml.nil? || rels_xml.empty?
|
|
1716
1904
|
|
|
1717
|
-
parser =
|
|
1905
|
+
parser = Ooxml::XmlParser.sax2_parser(rels_xml)
|
|
1718
1906
|
listener = Ooxml::Reader::RelsListener.new
|
|
1719
1907
|
parser.listen(listener)
|
|
1720
1908
|
parser.parse
|
|
@@ -1728,7 +1916,7 @@ module Xlsxrb
|
|
|
1728
1916
|
tbl_xml = zip_reader.read_entry(tbl_path)
|
|
1729
1917
|
next if tbl_xml.nil? || tbl_xml.empty?
|
|
1730
1918
|
|
|
1731
|
-
t_parser =
|
|
1919
|
+
t_parser = Ooxml::XmlParser.sax2_parser(tbl_xml)
|
|
1732
1920
|
t_listener = Ooxml::Reader::TableListener.new
|
|
1733
1921
|
t_parser.listen(t_listener)
|
|
1734
1922
|
t_parser.parse
|
|
@@ -1744,7 +1932,7 @@ module Xlsxrb
|
|
|
1744
1932
|
rels_xml = zip_reader.read_entry(rels_path)
|
|
1745
1933
|
return [] if rels_xml.nil? || rels_xml.empty?
|
|
1746
1934
|
|
|
1747
|
-
parser =
|
|
1935
|
+
parser = Ooxml::XmlParser.sax2_parser(rels_xml)
|
|
1748
1936
|
listener = Ooxml::Reader::RelsListener.new
|
|
1749
1937
|
parser.listen(listener)
|
|
1750
1938
|
parser.parse
|
|
@@ -1757,38 +1945,559 @@ module Xlsxrb
|
|
|
1757
1945
|
drawing_xml = zip_reader.read_entry(drawing_path)
|
|
1758
1946
|
return [] if drawing_xml.nil? || drawing_xml.empty?
|
|
1759
1947
|
|
|
1760
|
-
d_parser =
|
|
1948
|
+
d_parser = Ooxml::XmlParser.sax2_parser(drawing_xml)
|
|
1761
1949
|
d_listener = Ooxml::Reader::DrawingShapesListener.new
|
|
1762
1950
|
d_parser.listen(d_listener)
|
|
1763
1951
|
d_parser.parse
|
|
1764
1952
|
d_listener.shapes
|
|
1765
1953
|
end
|
|
1766
1954
|
|
|
1767
|
-
#: (
|
|
1955
|
+
#: (?zip_reader: Ooxml::ZipReader?, ?entry_name: String?) -> Array[Hash[Symbol, untyped]]
|
|
1956
|
+
def resolve_pivot_tables(zip_reader: nil, entry_name: nil)
|
|
1957
|
+
return [] unless zip_reader && entry_name
|
|
1958
|
+
|
|
1959
|
+
rels_path = entry_name.sub(%r{([^/]+)$}, '_rels/\1.rels')
|
|
1960
|
+
rels_xml = zip_reader.read_entry(rels_path)
|
|
1961
|
+
return [] if rels_xml.nil? || rels_xml.empty?
|
|
1962
|
+
|
|
1963
|
+
parser = Ooxml::XmlParser.sax2_parser(rels_xml)
|
|
1964
|
+
listener = Ooxml::Reader::RelsListener.new
|
|
1965
|
+
parser.listen(listener)
|
|
1966
|
+
parser.parse
|
|
1967
|
+
|
|
1968
|
+
pivot_rels = listener.relationships.select { |r| r[:type]&.end_with?("/pivotTable") }
|
|
1969
|
+
return [] if pivot_rels.empty?
|
|
1970
|
+
|
|
1971
|
+
base_dir = File.dirname(entry_name)
|
|
1972
|
+
pivot_rels.filter_map do |rel|
|
|
1973
|
+
pt_path = resolve_relative_path(base_dir, rel[:target])
|
|
1974
|
+
pt_xml = zip_reader.read_entry(pt_path)
|
|
1975
|
+
next if pt_xml.nil? || pt_xml.empty?
|
|
1976
|
+
|
|
1977
|
+
p_parser = Ooxml::XmlParser.sax2_parser(pt_xml)
|
|
1978
|
+
p_listener = Ooxml::Reader::PivotTableListener.new
|
|
1979
|
+
p_parser.listen(p_listener)
|
|
1980
|
+
p_parser.parse
|
|
1981
|
+
pt = p_listener.pivot_table
|
|
1982
|
+
next unless pt
|
|
1983
|
+
|
|
1984
|
+
pt_rels_path = pt_path.sub(%r{([^/]+)$}, '_rels/\1.rels')
|
|
1985
|
+
pt_rels_xml = zip_reader.read_entry(pt_rels_path)
|
|
1986
|
+
if pt_rels_xml && !pt_rels_xml.empty?
|
|
1987
|
+
c_parser = Ooxml::XmlParser.sax2_parser(pt_rels_xml)
|
|
1988
|
+
c_listener = Ooxml::Reader::RelsListener.new
|
|
1989
|
+
c_parser.listen(c_listener)
|
|
1990
|
+
c_parser.parse
|
|
1991
|
+
cache_rel = c_listener.relationships.find { |r| r[:type]&.end_with?("/pivotCacheDefinition") }
|
|
1992
|
+
if cache_rel
|
|
1993
|
+
c_path = resolve_relative_path(File.dirname(pt_path), cache_rel[:target])
|
|
1994
|
+
c_xml = zip_reader.read_entry(c_path)
|
|
1995
|
+
if c_xml && !c_xml.empty?
|
|
1996
|
+
cd_parser = Ooxml::XmlParser.sax2_parser(c_xml)
|
|
1997
|
+
cd_listener = Ooxml::Reader::PivotCacheDefinitionListener.new
|
|
1998
|
+
cd_parser.listen(cd_listener)
|
|
1999
|
+
cd_parser.parse
|
|
2000
|
+
cache_info = cd_listener.cache_definition
|
|
2001
|
+
if cache_info
|
|
2002
|
+
cd_rels_path = c_path.sub(%r{([^/]+)$}, '_rels/\1.rels')
|
|
2003
|
+
cd_rels_xml = zip_reader.read_entry(cd_rels_path)
|
|
2004
|
+
if cd_rels_xml && !cd_rels_xml.empty?
|
|
2005
|
+
rec_parser = Ooxml::XmlParser.sax2_parser(cd_rels_xml)
|
|
2006
|
+
rec_rels_listener = Ooxml::Reader::RelsListener.new
|
|
2007
|
+
rec_parser.listen(rec_rels_listener)
|
|
2008
|
+
rec_parser.parse
|
|
2009
|
+
rec_rel = rec_rels_listener.relationships.find { |r| r[:type]&.end_with?("/pivotCacheRecords") }
|
|
2010
|
+
if rec_rel
|
|
2011
|
+
rec_path = resolve_relative_path(File.dirname(c_path), rec_rel[:target])
|
|
2012
|
+
rec_xml = zip_reader.read_entry(rec_path)
|
|
2013
|
+
if rec_xml && !rec_xml.empty?
|
|
2014
|
+
r_parser = Ooxml::XmlParser.sax2_parser(rec_xml)
|
|
2015
|
+
r_listener = Ooxml::Reader::PivotCacheRecordsListener.new
|
|
2016
|
+
r_parser.listen(r_listener)
|
|
2017
|
+
r_parser.parse
|
|
2018
|
+
cache_info[:records] = r_listener.records unless r_listener.records.empty?
|
|
2019
|
+
end
|
|
2020
|
+
end
|
|
2021
|
+
end
|
|
2022
|
+
pt[:cache] = cache_info
|
|
2023
|
+
end
|
|
2024
|
+
end
|
|
2025
|
+
end
|
|
2026
|
+
end
|
|
2027
|
+
pt
|
|
2028
|
+
end
|
|
2029
|
+
end
|
|
2030
|
+
|
|
2031
|
+
#: (?zip_reader: Ooxml::ZipReader?, ?entry_name: String?) -> Array[Elements::Chart]
|
|
2032
|
+
def resolve_charts(zip_reader: nil, entry_name: nil)
|
|
2033
|
+
return [] unless zip_reader && entry_name
|
|
2034
|
+
|
|
2035
|
+
rels_path = entry_name.sub(%r{([^/]+)$}, '_rels/\1.rels')
|
|
2036
|
+
rels_xml = zip_reader.read_entry(rels_path)
|
|
2037
|
+
return [] if rels_xml.nil? || rels_xml.empty?
|
|
2038
|
+
|
|
2039
|
+
parser = Ooxml::XmlParser.sax2_parser(rels_xml)
|
|
2040
|
+
listener = Ooxml::Reader::RelsListener.new
|
|
2041
|
+
parser.listen(listener)
|
|
2042
|
+
parser.parse
|
|
2043
|
+
|
|
2044
|
+
drawing_rel = listener.relationships.find { |r| r[:type]&.end_with?("/drawing") }
|
|
2045
|
+
return [] unless drawing_rel
|
|
2046
|
+
|
|
2047
|
+
base_dir = File.dirname(entry_name)
|
|
2048
|
+
drawing_path = resolve_relative_path(base_dir, drawing_rel[:target])
|
|
2049
|
+
drawing_xml = zip_reader.read_entry(drawing_path)
|
|
2050
|
+
return [] if drawing_xml.nil? || drawing_xml.empty?
|
|
2051
|
+
|
|
2052
|
+
drawing_rels_path = drawing_path.sub(%r{([^/]+)$}, '_rels/\1.rels')
|
|
2053
|
+
drawing_rels_xml = zip_reader.read_entry(drawing_rels_path)
|
|
2054
|
+
drawing_rels = {}
|
|
2055
|
+
if drawing_rels_xml && !drawing_rels_xml.empty?
|
|
2056
|
+
d_parser = Ooxml::XmlParser.sax2_parser(drawing_rels_xml)
|
|
2057
|
+
d_listener = Ooxml::Reader::RelsListener.new
|
|
2058
|
+
d_parser.listen(d_listener)
|
|
2059
|
+
d_parser.parse
|
|
2060
|
+
d_listener.relationships.each do |r|
|
|
2061
|
+
drawing_rels[r[:id]] = r[:target]
|
|
2062
|
+
end
|
|
2063
|
+
end
|
|
2064
|
+
|
|
2065
|
+
d_parser = Ooxml::XmlParser.sax2_parser(drawing_xml)
|
|
2066
|
+
dc_listener = Ooxml::Reader::DrawingChartsListener.new
|
|
2067
|
+
d_parser.listen(dc_listener)
|
|
2068
|
+
d_parser.parse
|
|
2069
|
+
|
|
2070
|
+
drawing_dir = File.dirname(drawing_path)
|
|
2071
|
+
dc_listener.charts.map do |raw_chart|
|
|
2072
|
+
chart = raw_chart.dup
|
|
2073
|
+
target = drawing_rels[chart[:rid]]
|
|
2074
|
+
if target
|
|
2075
|
+
chart[:target] = target
|
|
2076
|
+
chart_path = resolve_relative_path(drawing_dir, target)
|
|
2077
|
+
chart_xml = zip_reader.read_entry(chart_path)
|
|
2078
|
+
if chart_xml && !chart_xml.empty?
|
|
2079
|
+
cp = Ooxml::XmlParser.sax2_parser(chart_xml)
|
|
2080
|
+
cl = Ooxml::Reader::ChartTypeListener.new
|
|
2081
|
+
cp.listen(cl)
|
|
2082
|
+
cp.parse
|
|
2083
|
+
chart[:chart_type] = cl.chart_type
|
|
2084
|
+
chart[:type] = cl.chart_type
|
|
2085
|
+
chart[:title] = cl.title
|
|
2086
|
+
chart[:title_overlay] = cl.title_overlay unless cl.title_overlay.nil?
|
|
2087
|
+
chart[:title_font] = cl.title_font if cl.title_font
|
|
2088
|
+
chart[:title_fill_color] = cl.title_fill_color if cl.title_fill_color
|
|
2089
|
+
chart[:title_no_fill] = cl.title_no_fill if cl.title_no_fill
|
|
2090
|
+
chart[:title_line_color] = cl.title_line_color if cl.title_line_color
|
|
2091
|
+
chart[:title_line_width] = cl.title_line_width if cl.title_line_width
|
|
2092
|
+
chart[:title_line_dash] = cl.title_line_dash if cl.title_line_dash
|
|
2093
|
+
chart[:series] = cl.series unless cl.series.empty?
|
|
2094
|
+
chart[:legend] = cl.legend unless cl.legend.empty?
|
|
2095
|
+
if cl.legend_font
|
|
2096
|
+
chart[:legend] ||= {}
|
|
2097
|
+
chart[:legend][:font] = cl.legend_font
|
|
2098
|
+
end
|
|
2099
|
+
chart[:data_labels] = cl.data_labels unless cl.data_labels.empty?
|
|
2100
|
+
chart[:cat_axis_title] = cl.cat_axis_title if cl.cat_axis_title
|
|
2101
|
+
chart[:val_axis_title] = cl.val_axis_title if cl.val_axis_title
|
|
2102
|
+
chart[:cat_axis_title_font] = cl.cat_axis_title_font if cl.cat_axis_title_font
|
|
2103
|
+
chart[:val_axis_title_font] = cl.val_axis_title_font if cl.val_axis_title_font
|
|
2104
|
+
chart[:cat_axis_title_fill] = cl.cat_axis_title_fill if cl.cat_axis_title_fill
|
|
2105
|
+
chart[:cat_axis_title_no_fill] = cl.cat_axis_title_no_fill if cl.cat_axis_title_no_fill
|
|
2106
|
+
chart[:cat_axis_title_line_color] = cl.cat_axis_title_line_color if cl.cat_axis_title_line_color
|
|
2107
|
+
chart[:cat_axis_title_line_width] = cl.cat_axis_title_line_width if cl.cat_axis_title_line_width
|
|
2108
|
+
chart[:cat_axis_title_line_dash] = cl.cat_axis_title_line_dash if cl.cat_axis_title_line_dash
|
|
2109
|
+
chart[:val_axis_title_fill] = cl.val_axis_title_fill if cl.val_axis_title_fill
|
|
2110
|
+
chart[:val_axis_title_no_fill] = cl.val_axis_title_no_fill if cl.val_axis_title_no_fill
|
|
2111
|
+
chart[:val_axis_title_line_color] = cl.val_axis_title_line_color if cl.val_axis_title_line_color
|
|
2112
|
+
chart[:val_axis_title_line_width] = cl.val_axis_title_line_width if cl.val_axis_title_line_width
|
|
2113
|
+
chart[:val_axis_title_line_dash] = cl.val_axis_title_line_dash if cl.val_axis_title_line_dash
|
|
2114
|
+
chart[:title_layout] = cl.title_layout if cl.title_layout
|
|
2115
|
+
chart[:cat_axis_title_layout] = cl.cat_axis_title_layout if cl.cat_axis_title_layout
|
|
2116
|
+
chart[:val_axis_title_layout] = cl.val_axis_title_layout if cl.val_axis_title_layout
|
|
2117
|
+
chart[:title_rotation] = cl.title_rotation if cl.title_rotation
|
|
2118
|
+
chart[:cat_axis_title_rotation] = cl.cat_axis_title_rotation if cl.cat_axis_title_rotation
|
|
2119
|
+
chart[:val_axis_title_rotation] = cl.val_axis_title_rotation if cl.val_axis_title_rotation
|
|
2120
|
+
chart[:grouping] = cl.grouping if cl.grouping
|
|
2121
|
+
chart[:bar_dir] = cl.bar_dir if cl.bar_dir
|
|
2122
|
+
chart[:vary_colors] = cl.vary_colors unless cl.vary_colors.nil?
|
|
2123
|
+
chart[:plot_vis_only] = cl.plot_vis_only unless cl.plot_vis_only.nil?
|
|
2124
|
+
chart[:disp_blanks_as] = cl.disp_blanks_as if cl.disp_blanks_as
|
|
2125
|
+
chart[:style] = cl.style if cl.style
|
|
2126
|
+
chart[:auto_title_deleted] = cl.auto_title_deleted unless cl.auto_title_deleted.nil?
|
|
2127
|
+
chart[:rounded_corners] = cl.rounded_corners unless cl.rounded_corners.nil?
|
|
2128
|
+
chart[:cat_axis_tick_lbl_pos] = cl.cat_axis_tick_lbl_pos if cl.cat_axis_tick_lbl_pos
|
|
2129
|
+
chart[:val_axis_tick_lbl_pos] = cl.val_axis_tick_lbl_pos if cl.val_axis_tick_lbl_pos
|
|
2130
|
+
chart[:cat_axis_major_gridlines] = cl.cat_axis_major_gridlines if cl.cat_axis_major_gridlines
|
|
2131
|
+
chart[:val_axis_major_gridlines] = cl.val_axis_major_gridlines if cl.val_axis_major_gridlines
|
|
2132
|
+
chart[:cat_axis_minor_gridlines] = cl.cat_axis_minor_gridlines if cl.cat_axis_minor_gridlines
|
|
2133
|
+
chart[:val_axis_minor_gridlines] = cl.val_axis_minor_gridlines if cl.val_axis_minor_gridlines
|
|
2134
|
+
chart[:show_d_lbls_over_max] = cl.show_d_lbls_over_max unless cl.show_d_lbls_over_max.nil?
|
|
2135
|
+
chart[:cat_axis_delete] = cl.cat_axis_delete unless cl.cat_axis_delete.nil?
|
|
2136
|
+
chart[:val_axis_delete] = cl.val_axis_delete unless cl.val_axis_delete.nil?
|
|
2137
|
+
chart[:cat_axis_orientation] = cl.cat_axis_orientation if cl.cat_axis_orientation
|
|
2138
|
+
chart[:val_axis_orientation] = cl.val_axis_orientation if cl.val_axis_orientation
|
|
2139
|
+
chart[:gap_width] = cl.gap_width if cl.gap_width
|
|
2140
|
+
chart[:overlap] = cl.overlap if cl.overlap
|
|
2141
|
+
chart[:gap_depth] = cl.gap_depth if cl.gap_depth
|
|
2142
|
+
chart[:bar_shape] = cl.bar_shape if cl.bar_shape
|
|
2143
|
+
chart[:bubble_3d] = cl.bubble_3d unless cl.bubble_3d.nil?
|
|
2144
|
+
chart[:bubble_scale] = cl.bubble_scale if cl.bubble_scale
|
|
2145
|
+
chart[:show_neg_bubbles] = cl.show_neg_bubbles unless cl.show_neg_bubbles.nil?
|
|
2146
|
+
chart[:size_represents] = cl.size_represents if cl.size_represents
|
|
2147
|
+
chart[:view_3d] = cl.view_3d if cl.view_3d
|
|
2148
|
+
chart[:cat_axis_num_fmt] = cl.cat_axis_num_fmt if cl.cat_axis_num_fmt
|
|
2149
|
+
chart[:val_axis_num_fmt] = cl.val_axis_num_fmt if cl.val_axis_num_fmt
|
|
2150
|
+
chart[:cat_axis_major_tick_mark] = cl.cat_axis_major_tick_mark if cl.cat_axis_major_tick_mark
|
|
2151
|
+
chart[:cat_axis_minor_tick_mark] = cl.cat_axis_minor_tick_mark if cl.cat_axis_minor_tick_mark
|
|
2152
|
+
chart[:val_axis_major_tick_mark] = cl.val_axis_major_tick_mark if cl.val_axis_major_tick_mark
|
|
2153
|
+
chart[:val_axis_minor_tick_mark] = cl.val_axis_minor_tick_mark if cl.val_axis_minor_tick_mark
|
|
2154
|
+
chart[:cat_axis_crosses] = cl.cat_axis_crosses if cl.cat_axis_crosses
|
|
2155
|
+
chart[:val_axis_crosses] = cl.val_axis_crosses if cl.val_axis_crosses
|
|
2156
|
+
chart[:cat_axis_crosses_at] = cl.cat_axis_crosses_at if cl.cat_axis_crosses_at
|
|
2157
|
+
chart[:val_axis_crosses_at] = cl.val_axis_crosses_at if cl.val_axis_crosses_at
|
|
2158
|
+
chart[:cat_axis_tick_lbl_skip] = cl.cat_axis_tick_lbl_skip if cl.cat_axis_tick_lbl_skip
|
|
2159
|
+
chart[:cat_axis_tick_mark_skip] = cl.cat_axis_tick_mark_skip if cl.cat_axis_tick_mark_skip
|
|
2160
|
+
chart[:cat_axis_lbl_offset] = cl.cat_axis_lbl_offset if cl.cat_axis_lbl_offset
|
|
2161
|
+
chart[:cat_axis_auto] = cl.cat_axis_auto unless cl.cat_axis_auto.nil?
|
|
2162
|
+
chart[:cat_axis_lbl_algn] = cl.cat_axis_lbl_algn if cl.cat_axis_lbl_algn
|
|
2163
|
+
chart[:cat_axis_no_multi_lvl_lbl] = cl.cat_axis_no_multi_lvl_lbl unless cl.cat_axis_no_multi_lvl_lbl.nil?
|
|
2164
|
+
chart[:val_axis_cross_between] = cl.val_axis_cross_between if cl.val_axis_cross_between
|
|
2165
|
+
chart[:val_axis_major_unit] = cl.val_axis_major_unit if cl.val_axis_major_unit
|
|
2166
|
+
chart[:val_axis_minor_unit] = cl.val_axis_minor_unit if cl.val_axis_minor_unit
|
|
2167
|
+
chart[:val_axis_disp_units] = cl.val_axis_disp_units if cl.val_axis_disp_units
|
|
2168
|
+
chart[:cat_axis_scaling_max] = cl.cat_axis_scaling_max if cl.cat_axis_scaling_max
|
|
2169
|
+
chart[:cat_axis_scaling_min] = cl.cat_axis_scaling_min if cl.cat_axis_scaling_min
|
|
2170
|
+
chart[:val_axis_scaling_max] = cl.val_axis_scaling_max if cl.val_axis_scaling_max
|
|
2171
|
+
chart[:val_axis_scaling_min] = cl.val_axis_scaling_min if cl.val_axis_scaling_min
|
|
2172
|
+
chart[:cat_axis_log_base] = cl.cat_axis_log_base if cl.cat_axis_log_base
|
|
2173
|
+
chart[:val_axis_log_base] = cl.val_axis_log_base if cl.val_axis_log_base
|
|
2174
|
+
chart[:first_slice_ang] = cl.first_slice_ang if cl.first_slice_ang
|
|
2175
|
+
chart[:hole_size] = cl.hole_size if cl.hole_size
|
|
2176
|
+
chart[:smooth] = cl.smooth unless cl.smooth.nil?
|
|
2177
|
+
chart[:marker] = cl.marker unless cl.marker.nil?
|
|
2178
|
+
chart[:drop_lines] = cl.drop_lines unless cl.drop_lines.nil?
|
|
2179
|
+
chart[:hi_low_lines] = cl.hi_low_lines unless cl.hi_low_lines.nil?
|
|
2180
|
+
chart[:ser_lines] = cl.ser_lines unless cl.ser_lines.nil?
|
|
2181
|
+
chart[:up_down_bars] = cl.up_down_bars if cl.up_down_bars
|
|
2182
|
+
chart[:scatter_style] = cl.scatter_style if cl.scatter_style
|
|
2183
|
+
chart[:radar_style] = cl.radar_style if cl.radar_style
|
|
2184
|
+
chart[:cat_axis_pos] = cl.cat_axis_pos if cl.cat_axis_pos
|
|
2185
|
+
chart[:val_axis_pos] = cl.val_axis_pos if cl.val_axis_pos
|
|
2186
|
+
chart[:wireframe] = cl.wireframe unless cl.wireframe.nil?
|
|
2187
|
+
chart[:band_fmts] = cl.band_fmts if cl.band_fmts
|
|
2188
|
+
chart[:of_pie_type] = cl.of_pie_type if cl.of_pie_type
|
|
2189
|
+
chart[:split_type] = cl.split_type if cl.split_type
|
|
2190
|
+
chart[:split_pos] = cl.split_pos if cl.split_pos
|
|
2191
|
+
chart[:cust_split] = cl.cust_split if cl.cust_split&.any?
|
|
2192
|
+
chart[:second_pie_size] = cl.second_pie_size if cl.second_pie_size
|
|
2193
|
+
chart[:data_table] = cl.data_table if cl.data_table
|
|
2194
|
+
chart[:plot_area_fill] = cl.plot_area_fill if cl.plot_area_fill
|
|
2195
|
+
chart[:plot_area_line_color] = cl.plot_area_line_color if cl.plot_area_line_color
|
|
2196
|
+
chart[:plot_area_line_width] = cl.plot_area_line_width if cl.plot_area_line_width
|
|
2197
|
+
chart[:plot_area_line_dash] = cl.plot_area_line_dash if cl.plot_area_line_dash
|
|
2198
|
+
chart[:plot_area_no_fill] = cl.plot_area_no_fill if cl.plot_area_no_fill
|
|
2199
|
+
chart[:plot_area_layout] = cl.plot_area_layout if cl.plot_area_layout
|
|
2200
|
+
chart[:cat_axis_label_rotation] = cl.cat_axis_label_rotation if cl.cat_axis_label_rotation
|
|
2201
|
+
chart[:val_axis_label_rotation] = cl.val_axis_label_rotation if cl.val_axis_label_rotation
|
|
2202
|
+
chart[:cat_axis_font] = cl.cat_axis_font if cl.cat_axis_font
|
|
2203
|
+
chart[:val_axis_font] = cl.val_axis_font if cl.val_axis_font
|
|
2204
|
+
chart[:cat_axis_fill] = cl.cat_axis_fill if cl.cat_axis_fill
|
|
2205
|
+
chart[:cat_axis_no_fill] = cl.cat_axis_no_fill if cl.cat_axis_no_fill
|
|
2206
|
+
chart[:val_axis_fill] = cl.val_axis_fill if cl.val_axis_fill
|
|
2207
|
+
chart[:val_axis_no_fill] = cl.val_axis_no_fill if cl.val_axis_no_fill
|
|
2208
|
+
chart[:cat_axis_line_color] = cl.cat_axis_line_color if cl.cat_axis_line_color
|
|
2209
|
+
chart[:cat_axis_line_width] = cl.cat_axis_line_width if cl.cat_axis_line_width
|
|
2210
|
+
chart[:cat_axis_line_dash] = cl.cat_axis_line_dash if cl.cat_axis_line_dash
|
|
2211
|
+
chart[:val_axis_line_color] = cl.val_axis_line_color if cl.val_axis_line_color
|
|
2212
|
+
chart[:val_axis_line_width] = cl.val_axis_line_width if cl.val_axis_line_width
|
|
2213
|
+
chart[:val_axis_line_dash] = cl.val_axis_line_dash if cl.val_axis_line_dash
|
|
2214
|
+
chart[:floor] = cl.floor if cl.floor
|
|
2215
|
+
chart[:side_wall] = cl.side_wall if cl.side_wall
|
|
2216
|
+
chart[:back_wall] = cl.back_wall if cl.back_wall
|
|
2217
|
+
chart[:cat_axis_type] = cl.cat_axis_type if cl.cat_axis_type
|
|
2218
|
+
chart[:cat_axis_base_time_unit] = cl.cat_axis_base_time_unit if cl.cat_axis_base_time_unit
|
|
2219
|
+
chart[:cat_axis_major_time_unit] = cl.cat_axis_major_time_unit if cl.cat_axis_major_time_unit
|
|
2220
|
+
chart[:cat_axis_minor_time_unit] = cl.cat_axis_minor_time_unit if cl.cat_axis_minor_time_unit
|
|
2221
|
+
chart[:cat_axis_major_unit] = cl.cat_axis_major_unit if cl.cat_axis_major_unit
|
|
2222
|
+
chart[:cat_axis_minor_unit] = cl.cat_axis_minor_unit if cl.cat_axis_minor_unit
|
|
2223
|
+
chart[:chart_fill] = cl.chart_fill if cl.chart_fill
|
|
2224
|
+
chart[:chart_no_fill] = cl.chart_no_fill if cl.chart_no_fill
|
|
2225
|
+
chart[:chart_line_color] = cl.chart_line_color if cl.chart_line_color
|
|
2226
|
+
chart[:chart_line_width] = cl.chart_line_width if cl.chart_line_width
|
|
2227
|
+
chart[:chart_line_dash] = cl.chart_line_dash if cl.chart_line_dash
|
|
2228
|
+
chart[:protection] = cl.protection if cl.protection
|
|
2229
|
+
chart[:print_settings] = cl.print_settings if cl.print_settings
|
|
2230
|
+
chart[:chart_font] = cl.chart_font if cl.chart_font
|
|
2231
|
+
ca = {
|
|
2232
|
+
title: cl.cat_axis_title,
|
|
2233
|
+
major_gridlines: cl.cat_axis_major_gridlines,
|
|
2234
|
+
minor_gridlines: cl.cat_axis_minor_gridlines,
|
|
2235
|
+
num_fmt: cl.cat_axis_num_fmt,
|
|
2236
|
+
pos: cl.cat_axis_pos,
|
|
2237
|
+
max: cl.cat_axis_scaling_max,
|
|
2238
|
+
min: cl.cat_axis_scaling_min,
|
|
2239
|
+
major_unit: cl.cat_axis_major_unit,
|
|
2240
|
+
minor_unit: cl.cat_axis_minor_unit,
|
|
2241
|
+
delete: cl.cat_axis_delete
|
|
2242
|
+
}.compact
|
|
2243
|
+
chart[:category_axis] = ca unless ca.empty?
|
|
2244
|
+
|
|
2245
|
+
va = {
|
|
2246
|
+
title: cl.val_axis_title,
|
|
2247
|
+
major_gridlines: cl.val_axis_major_gridlines,
|
|
2248
|
+
minor_gridlines: cl.val_axis_minor_gridlines,
|
|
2249
|
+
num_fmt: cl.val_axis_num_fmt,
|
|
2250
|
+
pos: cl.val_axis_pos,
|
|
2251
|
+
max: cl.val_axis_scaling_max,
|
|
2252
|
+
min: cl.val_axis_scaling_min,
|
|
2253
|
+
major_unit: cl.val_axis_major_unit,
|
|
2254
|
+
minor_unit: cl.val_axis_minor_unit,
|
|
2255
|
+
delete: cl.val_axis_delete
|
|
2256
|
+
}.compact
|
|
2257
|
+
chart[:value_axis] = va unless va.empty?
|
|
2258
|
+
|
|
2259
|
+
chart[:sec_val_axis_title] = cl.sec_val_axis_title if cl.sec_val_axis_title
|
|
2260
|
+
chart[:sec_val_axis_major_gridlines] = cl.sec_val_axis_major_gridlines if cl.sec_val_axis_major_gridlines
|
|
2261
|
+
chart[:sec_val_axis_minor_gridlines] = cl.sec_val_axis_minor_gridlines if cl.sec_val_axis_minor_gridlines
|
|
2262
|
+
chart[:sec_val_axis_num_fmt] = cl.sec_val_axis_num_fmt if cl.sec_val_axis_num_fmt
|
|
2263
|
+
chart[:sec_val_axis_pos] = cl.sec_val_axis_pos if cl.sec_val_axis_pos
|
|
2264
|
+
chart[:sec_val_axis_scaling_max] = cl.sec_val_axis_scaling_max if cl.sec_val_axis_scaling_max
|
|
2265
|
+
chart[:sec_val_axis_scaling_min] = cl.sec_val_axis_scaling_min if cl.sec_val_axis_scaling_min
|
|
2266
|
+
chart[:sec_val_axis_major_unit] = cl.sec_val_axis_major_unit if cl.sec_val_axis_major_unit
|
|
2267
|
+
chart[:sec_val_axis_minor_unit] = cl.sec_val_axis_minor_unit if cl.sec_val_axis_minor_unit
|
|
2268
|
+
if cl.sec_val_axis_title || cl.sec_val_axis_major_gridlines || cl.sec_val_axis_scaling_max ||
|
|
2269
|
+
cl.sec_val_axis_scaling_min || cl.sec_val_axis_num_fmt || cl.sec_val_axis_pos
|
|
2270
|
+
sva = {
|
|
2271
|
+
title: cl.sec_val_axis_title,
|
|
2272
|
+
major_gridlines: cl.sec_val_axis_major_gridlines,
|
|
2273
|
+
minor_gridlines: cl.sec_val_axis_minor_gridlines,
|
|
2274
|
+
num_fmt: cl.sec_val_axis_num_fmt,
|
|
2275
|
+
pos: cl.sec_val_axis_pos,
|
|
2276
|
+
max: cl.sec_val_axis_scaling_max,
|
|
2277
|
+
min: cl.sec_val_axis_scaling_min,
|
|
2278
|
+
major_unit: cl.sec_val_axis_major_unit,
|
|
2279
|
+
minor_unit: cl.sec_val_axis_minor_unit
|
|
2280
|
+
}.compact
|
|
2281
|
+
chart[:secondary_value_axis] = sva unless sva.empty?
|
|
2282
|
+
end
|
|
2283
|
+
end
|
|
2284
|
+
end
|
|
2285
|
+
from_col = chart.delete(:from_col)
|
|
2286
|
+
to_col = chart.delete(:to_col)
|
|
2287
|
+
chart[:from_column] ||= from_col if from_col
|
|
2288
|
+
chart[:to_column] ||= to_col if to_col
|
|
2289
|
+
rid = chart.delete(:rid)
|
|
2290
|
+
chart[:r_id] ||= rid if rid
|
|
2291
|
+
ctype = chart.delete(:chart_type)
|
|
2292
|
+
chart[:type] ||= ctype if ctype
|
|
2293
|
+
Elements::Chart.new(**chart)
|
|
2294
|
+
end
|
|
2295
|
+
end
|
|
2296
|
+
|
|
2297
|
+
#: (String? sheet_xml) -> Array[Elements::SparklineGroup]
|
|
2298
|
+
def resolve_sparkline_groups(sheet_xml)
|
|
2299
|
+
return [] if sheet_xml.nil? || !sheet_xml.include?("sparklineGroup")
|
|
2300
|
+
|
|
2301
|
+
listener = Ooxml::Reader::SparklineGroupsListener.new
|
|
2302
|
+
parser = Ooxml::XmlParser.sax2_parser(sheet_xml)
|
|
2303
|
+
parser.listen(listener)
|
|
2304
|
+
parser.parse
|
|
2305
|
+
listener.groups.map do |grp|
|
|
2306
|
+
grp.is_a?(Elements::SparklineGroup) ? grp : Elements::SparklineGroup.new(**grp)
|
|
2307
|
+
end
|
|
2308
|
+
end
|
|
2309
|
+
|
|
2310
|
+
#: (String? sheet_xml, ?zip_reader: Ooxml::ZipReader?, ?entry_name: String?) -> Array[Elements::HeaderFooterImage]
|
|
2311
|
+
def resolve_header_footer_images(sheet_xml, zip_reader: nil, entry_name: nil)
|
|
2312
|
+
return [] unless sheet_xml && zip_reader && entry_name
|
|
2313
|
+
return [] unless sheet_xml.include?("legacyDrawingHF")
|
|
2314
|
+
|
|
2315
|
+
m = sheet_xml.match(/<(?:[a-zA-Z0-9_]+:)?legacyDrawingHF\b[^>]*\br:id=["']([^"']+)["']/)
|
|
2316
|
+
return [] unless m
|
|
2317
|
+
|
|
2318
|
+
hf_rid = m[1]
|
|
2319
|
+
rels_path = entry_name.sub(%r{([^/]+)$}, '_rels/\1.rels')
|
|
2320
|
+
rels_xml = zip_reader.read_entry(rels_path)
|
|
2321
|
+
return [] if rels_xml.nil? || rels_xml.empty?
|
|
2322
|
+
|
|
2323
|
+
parser = Ooxml::XmlParser.sax2_parser(rels_xml)
|
|
2324
|
+
listener = Ooxml::Reader::RelsListener.new
|
|
2325
|
+
parser.listen(listener)
|
|
2326
|
+
parser.parse
|
|
2327
|
+
|
|
2328
|
+
vml_rel = listener.relationships.find { |r| r[:id] == hf_rid }
|
|
2329
|
+
return [] unless vml_rel
|
|
2330
|
+
|
|
2331
|
+
base_dir = File.dirname(entry_name)
|
|
2332
|
+
vml_path = resolve_relative_path(base_dir, vml_rel[:target])
|
|
2333
|
+
vml_xml = zip_reader.read_entry(vml_path)
|
|
2334
|
+
return [] if vml_xml.nil? || vml_xml.empty?
|
|
2335
|
+
|
|
2336
|
+
vml_rels_path = vml_path.sub(%r{([^/]+)$}, '_rels/\1.rels')
|
|
2337
|
+
vml_rels_xml = zip_reader.read_entry(vml_rels_path)
|
|
2338
|
+
vml_rels = {}
|
|
2339
|
+
if vml_rels_xml && !vml_rels_xml.empty?
|
|
2340
|
+
vr_parser = Ooxml::XmlParser.sax2_parser(vml_rels_xml)
|
|
2341
|
+
vr_listener = Ooxml::Reader::RelsListener.new
|
|
2342
|
+
vr_parser.listen(vr_listener)
|
|
2343
|
+
vr_parser.parse
|
|
2344
|
+
vr_listener.relationships.each do |r|
|
|
2345
|
+
vml_rels[r[:id]] = r[:target]
|
|
2346
|
+
end
|
|
2347
|
+
end
|
|
2348
|
+
|
|
2349
|
+
vml_parser = Ooxml::XmlParser.sax2_parser(vml_xml)
|
|
2350
|
+
hf_listener = Ooxml::Reader::VmlHeaderFooterListener.new
|
|
2351
|
+
vml_parser.listen(hf_listener)
|
|
2352
|
+
vml_parser.parse
|
|
2353
|
+
|
|
2354
|
+
vml_dir = File.dirname(vml_path)
|
|
2355
|
+
hf_listener.shapes.filter_map do |shape|
|
|
2356
|
+
rel_id = shape[:rel_id]
|
|
2357
|
+
media_target = vml_rels[rel_id]
|
|
2358
|
+
next unless media_target
|
|
2359
|
+
|
|
2360
|
+
media_path = resolve_relative_path(vml_dir, media_target)
|
|
2361
|
+
img_data = zip_reader.read_entry(media_path)
|
|
2362
|
+
next unless img_data
|
|
2363
|
+
|
|
2364
|
+
img_data = img_data.b
|
|
2365
|
+
ext = File.extname(media_path).delete_prefix(".").downcase
|
|
2366
|
+
content_type = case ext
|
|
2367
|
+
when "png" then "image/png"
|
|
2368
|
+
when "jpg", "jpeg" then "image/jpeg"
|
|
2369
|
+
when "gif" then "image/gif"
|
|
2370
|
+
when "emf" then "image/x-emf"
|
|
2371
|
+
when "wmf" then "image/x-wmf"
|
|
2372
|
+
else "application/octet-stream"
|
|
2373
|
+
end
|
|
2374
|
+
|
|
2375
|
+
Elements::HeaderFooterImage.new(
|
|
2376
|
+
position: shape[:id],
|
|
2377
|
+
r_id: rel_id,
|
|
2378
|
+
path: media_path,
|
|
2379
|
+
extension: ext,
|
|
2380
|
+
data: img_data,
|
|
2381
|
+
content_type: content_type
|
|
2382
|
+
)
|
|
2383
|
+
end
|
|
2384
|
+
end
|
|
2385
|
+
|
|
2386
|
+
#: (Array[untyped]? defined_names, String? sheet_name, Integer? sheet_index) -> String?
|
|
2387
|
+
def extract_sheet_print_area(defined_names, sheet_name, sheet_index)
|
|
2388
|
+
return nil unless defined_names && !defined_names.empty?
|
|
2389
|
+
|
|
2390
|
+
dn = defined_names.find do |d|
|
|
2391
|
+
d_name = d.respond_to?(:name) ? d.name : (d[:name] || d["name"])
|
|
2392
|
+
d_name == "_xlnm.Print_Area" && match_sheet_defined_name?(d, sheet_name, sheet_index)
|
|
2393
|
+
end
|
|
2394
|
+
return nil unless dn
|
|
2395
|
+
|
|
2396
|
+
val = dn.respond_to?(:value) ? dn.value : (dn[:value] || dn["value"])
|
|
2397
|
+
return nil unless val && !val.empty?
|
|
2398
|
+
|
|
2399
|
+
val.split(",").map { |part| part.sub(/\A(?:'(?:''|[^'])*'|[^!]+)!/, "").delete("$").strip }.join(",")
|
|
2400
|
+
end
|
|
2401
|
+
|
|
2402
|
+
#: (Array[untyped]? defined_names, String? sheet_name, Integer? sheet_index) -> Elements::PrintTitles?
|
|
2403
|
+
def extract_sheet_print_titles(defined_names, sheet_name, sheet_index)
|
|
2404
|
+
return nil unless defined_names && !defined_names.empty?
|
|
2405
|
+
|
|
2406
|
+
dn = defined_names.find do |d|
|
|
2407
|
+
d_name = d.respond_to?(:name) ? d.name : (d[:name] || d["name"])
|
|
2408
|
+
d_name == "_xlnm.Print_Titles" && match_sheet_defined_name?(d, sheet_name, sheet_index)
|
|
2409
|
+
end
|
|
2410
|
+
return nil unless dn
|
|
2411
|
+
|
|
2412
|
+
val = dn.respond_to?(:value) ? dn.value : (dn[:value] || dn["value"])
|
|
2413
|
+
return nil unless val && !val.empty?
|
|
2414
|
+
|
|
2415
|
+
rows = nil
|
|
2416
|
+
cols = nil
|
|
2417
|
+
val.split(",").each do |raw_part|
|
|
2418
|
+
part = raw_part.sub(/\A(?:'(?:''|[^'])*'|[^!]+)!/, "").delete("$").strip
|
|
2419
|
+
if part =~ /\A\d+(?::\d+)?\z/
|
|
2420
|
+
rows = part
|
|
2421
|
+
elsif part =~ /\A[A-Za-z]+(?::[A-Za-z]+)?\z/
|
|
2422
|
+
cols = part
|
|
2423
|
+
end
|
|
2424
|
+
end
|
|
2425
|
+
|
|
2426
|
+
return nil if rows.nil? && cols.nil?
|
|
2427
|
+
|
|
2428
|
+
Elements::PrintTitles.new(rows: rows, columns: cols)
|
|
2429
|
+
end
|
|
2430
|
+
|
|
2431
|
+
#: (untyped defined_name, String? sheet_name, Integer? sheet_index) -> bool
|
|
2432
|
+
def match_sheet_defined_name?(defined_name, sheet_name, sheet_index)
|
|
2433
|
+
d_id = if defined_name.respond_to?(:local_sheet_id)
|
|
2434
|
+
defined_name.local_sheet_id
|
|
2435
|
+
else
|
|
2436
|
+
defined_name[:local_sheet_id] || defined_name["local_sheet_id"]
|
|
2437
|
+
end
|
|
2438
|
+
d_name = if defined_name.respond_to?(:local_sheet_name)
|
|
2439
|
+
defined_name.local_sheet_name
|
|
2440
|
+
else
|
|
2441
|
+
defined_name[:local_sheet_name] || defined_name["local_sheet_name"] ||
|
|
2442
|
+
(defined_name.respond_to?(:sheet) ? defined_name.sheet : defined_name[:sheet])
|
|
2443
|
+
end
|
|
2444
|
+
d_val = defined_name.respond_to?(:value) ? defined_name.value : (defined_name[:value] || defined_name["value"])
|
|
2445
|
+
|
|
2446
|
+
return true if !d_id.nil? && !sheet_index.nil? && d_id.to_i == sheet_index
|
|
2447
|
+
return true if d_name && sheet_name && d_name.to_s == sheet_name.to_s
|
|
2448
|
+
|
|
2449
|
+
if d_id.nil? && sheet_name && d_val
|
|
2450
|
+
quoted = Regexp.escape(sheet_name)
|
|
2451
|
+
return true if d_val =~ /\A(?:'#{quoted}'|#{quoted})!/
|
|
2452
|
+
end
|
|
2453
|
+
false
|
|
2454
|
+
end
|
|
2455
|
+
|
|
2456
|
+
#: (untyped raw_row, ?Hash[String, untyped] hyperlinks, ?(Array[untyped] | Hash[String, untyped]) comments, ?Hash[untyped, untyped]? styles, ?date1904: bool, ?threaded_comments: (Array[untyped] | Hash[String, untyped])) -> (Elements::Row | untyped)
|
|
1768
2457
|
def build_row_from_raw(raw_row, hyperlinks = {}, comments = [], styles = nil, date1904: false, threaded_comments: [])
|
|
1769
2458
|
return raw_row if raw_row.is_a?(Elements::Row)
|
|
1770
2459
|
|
|
1771
2460
|
comments_map = if comments.is_a?(Hash)
|
|
1772
|
-
comments
|
|
2461
|
+
comments.each_with_object({}) do |(k, c), acc|
|
|
2462
|
+
acc[k.to_s.upcase] = c.is_a?(Elements::Comment) ? c : Elements::Comment.new(**c)
|
|
2463
|
+
end
|
|
1773
2464
|
else
|
|
1774
|
-
comments.each_with_object({})
|
|
2465
|
+
comments.each_with_object({}) do |c, acc|
|
|
2466
|
+
obj = c.is_a?(Elements::Comment) ? c : Elements::Comment.new(**c)
|
|
2467
|
+
r = obj.ref
|
|
2468
|
+
acc[r.to_s.upcase] = obj if r
|
|
2469
|
+
end
|
|
1775
2470
|
end
|
|
1776
2471
|
|
|
1777
2472
|
threaded_comments_map = if threaded_comments.is_a?(Hash)
|
|
1778
|
-
threaded_comments
|
|
2473
|
+
threaded_comments.each_with_object({}) do |(k, tcs), acc|
|
|
2474
|
+
arr = Array(tcs).map do |tc|
|
|
2475
|
+
tc.is_a?(Elements::ThreadedComment) ? tc : Elements::ThreadedComment.new(**tc)
|
|
2476
|
+
end
|
|
2477
|
+
acc[k.to_s.upcase] = arr
|
|
2478
|
+
end
|
|
1779
2479
|
else
|
|
1780
2480
|
threaded_comments.each_with_object({}) do |c, acc|
|
|
1781
|
-
|
|
1782
|
-
|
|
2481
|
+
obj = c.is_a?(Elements::ThreadedComment) ? c : Elements::ThreadedComment.new(**c)
|
|
2482
|
+
r = obj.ref
|
|
2483
|
+
(acc[r.to_s.upcase] ||= []) << obj if r
|
|
1783
2484
|
end
|
|
1784
2485
|
end
|
|
1785
2486
|
|
|
1786
|
-
|
|
2487
|
+
hyperlinks_map = if hyperlinks && !hyperlinks.empty?
|
|
2488
|
+
hyperlinks.each_with_object({}) do |(k, hl), acc|
|
|
2489
|
+
acc[k.to_s.upcase] = hl.is_a?(Elements::Hyperlink) ? hl : Elements::Hyperlink.new(**hl)
|
|
2490
|
+
end
|
|
2491
|
+
else
|
|
2492
|
+
{}
|
|
2493
|
+
end
|
|
2494
|
+
|
|
2495
|
+
raw_cells = raw_row.respond_to?(:cells) ? raw_row.cells : raw_row[:cells]
|
|
1787
2496
|
cells = raw_cells.map do |rc|
|
|
1788
2497
|
if rc.is_a?(Elements::Cell)
|
|
1789
|
-
hl =
|
|
1790
|
-
cm = comments_map
|
|
1791
|
-
tcs = threaded_comments_map
|
|
2498
|
+
hl = hyperlinks_map[rc.ref]
|
|
2499
|
+
cm = comments_map[rc.ref]
|
|
2500
|
+
tcs = threaded_comments_map[rc.ref]
|
|
1792
2501
|
fmt = rc.format_code || (NumberFormatter.format_code_for(rc.style_index, styles) if styles && rc.style_index)
|
|
1793
2502
|
if hl || cm || tcs || (fmt && rc.format_code != fmt) || (date1904 && !rc.date1904?)
|
|
1794
2503
|
rc.with(
|
|
@@ -1802,13 +2511,18 @@ module Xlsxrb
|
|
|
1802
2511
|
rc
|
|
1803
2512
|
end
|
|
1804
2513
|
else
|
|
1805
|
-
parsed = Elements::Cell.
|
|
1806
|
-
row_idx =
|
|
2514
|
+
parsed = Elements::Cell._parse_ref(rc[:ref]) if rc[:ref]
|
|
2515
|
+
row_idx = if parsed
|
|
2516
|
+
parsed[0]
|
|
2517
|
+
else
|
|
2518
|
+
(raw_row.respond_to?(:index) ? raw_row.index : raw_row[:index])
|
|
2519
|
+
end
|
|
1807
2520
|
col_idx = parsed ? parsed[1] : 0
|
|
1808
|
-
ref = rc[:ref] || "#{Elements::Cell.
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
2521
|
+
ref = rc[:ref] || "#{Elements::Cell._column_letter(col_idx)}#{row_idx + 1}"
|
|
2522
|
+
ref_key = ref.upcase
|
|
2523
|
+
hl = hyperlinks_map[ref_key]
|
|
2524
|
+
cm = comments_map[ref_key]
|
|
2525
|
+
tcs = threaded_comments_map[ref_key]
|
|
1812
2526
|
fmt = rc[:format_code] || (NumberFormatter.format_code_for(rc[:style_index], styles) if styles && rc[:style_index])
|
|
1813
2527
|
|
|
1814
2528
|
val = rc[:value]
|
|
@@ -1836,115 +2550,36 @@ module Xlsxrb
|
|
|
1836
2550
|
)
|
|
1837
2551
|
end
|
|
1838
2552
|
end
|
|
1839
|
-
attrs = raw_row[:attrs] || {}
|
|
1840
|
-
|
|
1841
|
-
if
|
|
2553
|
+
attrs = raw_row.respond_to?(:attributes) ? raw_row.attributes : (raw_row[:attrs] || {})
|
|
2554
|
+
row_idx = raw_row.respond_to?(:index) ? raw_row.index : raw_row[:index]
|
|
2555
|
+
row_source = if raw_row.respond_to?(:source)
|
|
2556
|
+
raw_row.source
|
|
2557
|
+
else
|
|
2558
|
+
(raw_row.is_a?(Hash) ? raw_row[:source] : nil)
|
|
2559
|
+
end
|
|
2560
|
+
row_errors = Elements::Row.validate(row_idx, cells)
|
|
2561
|
+
if !row_errors.empty? && row_source
|
|
1842
2562
|
# simplecov:disable
|
|
1843
2563
|
# Edge case / untested delegation block
|
|
1844
2564
|
row_errors = row_errors.map do |err|
|
|
1845
|
-
"#{err} (at #{
|
|
2565
|
+
"#{err} (at #{row_source[:part]} row #{row_source[:row] + 1})"
|
|
1846
2566
|
# simplecov:enable
|
|
1847
2567
|
end
|
|
1848
2568
|
end
|
|
1849
|
-
row_unmapped = {}
|
|
1850
|
-
row_unmapped[:style_index] = attrs[:style_index] if attrs[:style_index]
|
|
1851
2569
|
Elements::Row.new(
|
|
1852
|
-
index:
|
|
2570
|
+
index: row_idx,
|
|
1853
2571
|
cells: cells,
|
|
1854
2572
|
height: attrs[:height],
|
|
1855
2573
|
hidden: attrs[:hidden] || false,
|
|
1856
2574
|
custom_height: attrs[:custom_height] || false,
|
|
1857
2575
|
collapsed: attrs[:collapsed] || false,
|
|
1858
2576
|
outline_level: attrs[:outline_level],
|
|
1859
|
-
|
|
2577
|
+
style_index: attrs[:style_index],
|
|
2578
|
+
unmapped_data: Elements::EMPTY_HASH,
|
|
1860
2579
|
errors: row_errors
|
|
1861
2580
|
)
|
|
1862
2581
|
end
|
|
1863
2582
|
|
|
1864
|
-
#: (Elements::Cell cell, Array[String] sst, Hash[String, Integer] sst_index, ?date1904: bool) -> Hash[Symbol, untyped]
|
|
1865
|
-
def build_raw_cell(cell, sst, sst_index, date1904: false)
|
|
1866
|
-
# simplecov:disable
|
|
1867
|
-
# Edge case / untested delegation block
|
|
1868
|
-
ref = cell.ref
|
|
1869
|
-
value = cell.value
|
|
1870
|
-
result = { ref: ref, style_index: cell.style_index }
|
|
1871
|
-
|
|
1872
|
-
case value
|
|
1873
|
-
when String, Xlsxrb::Elements::RichText
|
|
1874
|
-
idx = sst_index[value] ||= begin
|
|
1875
|
-
sst << value
|
|
1876
|
-
sst.size - 1
|
|
1877
|
-
end
|
|
1878
|
-
result[:value] = idx
|
|
1879
|
-
result[:type] = "s"
|
|
1880
|
-
when true, false
|
|
1881
|
-
result[:value] = value
|
|
1882
|
-
result[:type] = "b"
|
|
1883
|
-
when Integer, Float
|
|
1884
|
-
result[:value] = value
|
|
1885
|
-
when Xlsxrb::Elements::CellError
|
|
1886
|
-
result[:value] = value.code
|
|
1887
|
-
result[:type] = "e"
|
|
1888
|
-
when Date
|
|
1889
|
-
result[:value] = Xlsxrb::Ooxml::Utils.date_to_serial(value, date1904: date1904)
|
|
1890
|
-
when Time
|
|
1891
|
-
result[:value] = Xlsxrb::Ooxml::Utils.datetime_to_serial(value, date1904: date1904)
|
|
1892
|
-
# simplecov:enable
|
|
1893
|
-
when NilClass
|
|
1894
|
-
# empty cell
|
|
1895
|
-
end
|
|
1896
|
-
|
|
1897
|
-
# simplecov:disable
|
|
1898
|
-
# Edge case / untested delegation block
|
|
1899
|
-
if cell.formula
|
|
1900
|
-
f = cell.formula
|
|
1901
|
-
if f.is_a?(Elements::Formula)
|
|
1902
|
-
result[:formula] = f.expression
|
|
1903
|
-
result[:formula_type] = f.type if f.type
|
|
1904
|
-
result[:formula_ref] = f.ref if f.ref
|
|
1905
|
-
result[:formula_si] = f.shared_index if f.shared_index
|
|
1906
|
-
result[:formula_ca] = true if f.calculate_always
|
|
1907
|
-
unless f.cached_value.nil?
|
|
1908
|
-
# Cached value is written as-is (not through SST)
|
|
1909
|
-
result[:value] = f.cached_value
|
|
1910
|
-
case f.cached_value
|
|
1911
|
-
when true, false
|
|
1912
|
-
result[:type] = "b"
|
|
1913
|
-
when Elements::CellError
|
|
1914
|
-
result[:type] = "e"
|
|
1915
|
-
result[:value] = f.cached_value.code
|
|
1916
|
-
else
|
|
1917
|
-
result.delete(:type) # Ensure no type is set; cached values are plain text in <v>
|
|
1918
|
-
end
|
|
1919
|
-
# simplecov:enable
|
|
1920
|
-
end
|
|
1921
|
-
else
|
|
1922
|
-
# simplecov:disable
|
|
1923
|
-
# Edge case / untested delegation block
|
|
1924
|
-
result[:formula] = f
|
|
1925
|
-
# simplecov:enable
|
|
1926
|
-
end
|
|
1927
|
-
end
|
|
1928
|
-
# simplecov:disable
|
|
1929
|
-
# Edge case / untested delegation block
|
|
1930
|
-
result
|
|
1931
|
-
# simplecov:enable
|
|
1932
|
-
end
|
|
1933
|
-
|
|
1934
|
-
#: (Elements::Row row) -> Hash[Symbol, untyped]
|
|
1935
|
-
def build_row_attrs(row)
|
|
1936
|
-
# simplecov:disable
|
|
1937
|
-
# Edge case / untested delegation block
|
|
1938
|
-
attrs = {}
|
|
1939
|
-
attrs[:height] = row.height if row.height
|
|
1940
|
-
attrs[:hidden] = true if row.hidden
|
|
1941
|
-
attrs[:custom_height] = true if row.custom_height
|
|
1942
|
-
attrs[:collapsed] = true if row.collapsed
|
|
1943
|
-
attrs[:outline_level] = row.outline_level if row.outline_level
|
|
1944
|
-
attrs
|
|
1945
|
-
# simplecov:enable
|
|
1946
|
-
end
|
|
1947
|
-
|
|
1948
2583
|
#: (untyped source, String? password) -> untyped
|
|
1949
2584
|
def prepare_source_io(source, password)
|
|
1950
2585
|
if source.is_a?(String)
|
|
@@ -1970,7 +2605,12 @@ module Xlsxrb
|
|
|
1970
2605
|
source
|
|
1971
2606
|
end
|
|
1972
2607
|
else
|
|
1973
|
-
|
|
2608
|
+
# Not XLSX or encrypted bytes and not an existing file: report the path rather than
|
|
2609
|
+
# parsing the path string itself as ZIP content.
|
|
2610
|
+
raise Errno::EISDIR, source if File.directory?(source)
|
|
2611
|
+
|
|
2612
|
+
shown = source.length > 200 || source.include?("\n") ? "#{source[0, 60].inspect}... (#{source.bytesize} bytes)" : source
|
|
2613
|
+
raise Errno::ENOENT, shown
|
|
1974
2614
|
end
|
|
1975
2615
|
elsif source.respond_to?(:read) && source.respond_to?(:pos) && source.respond_to?(:seek)
|
|
1976
2616
|
begin
|
|
@@ -1991,522 +2631,5 @@ module Xlsxrb
|
|
|
1991
2631
|
source
|
|
1992
2632
|
end
|
|
1993
2633
|
end
|
|
1994
|
-
|
|
1995
|
-
#: (untyped dest, Ooxml::ZipReader zip_reader, Hash[String, String] replaced_entries, ?password: String?) -> void
|
|
1996
|
-
def perform_modify_write(dest, zip_reader, replaced_entries, password: nil)
|
|
1997
|
-
norm_replaced = {}
|
|
1998
|
-
replaced_entries.each do |k, v|
|
|
1999
|
-
norm_replaced[k.tr("\\", "/").downcase] = [k.tr("\\", "/"), v]
|
|
2000
|
-
end
|
|
2001
|
-
|
|
2002
|
-
write_zip = lambda do |zip_out|
|
|
2003
|
-
Ooxml::ZipWriter.open(zip_out) do |zip_writer|
|
|
2004
|
-
written_keys = Set.new
|
|
2005
|
-
|
|
2006
|
-
zip_reader.entry_names.each do |name|
|
|
2007
|
-
norm_name = name.tr("\\", "/").downcase
|
|
2008
|
-
next if written_keys.include?(norm_name)
|
|
2009
|
-
|
|
2010
|
-
written_keys << norm_name
|
|
2011
|
-
canonical_path = name.tr("\\", "/")
|
|
2012
|
-
|
|
2013
|
-
if norm_replaced.key?(norm_name)
|
|
2014
|
-
_orig_key, content = norm_replaced[norm_name]
|
|
2015
|
-
zip_writer.add_entry(canonical_path, content)
|
|
2016
|
-
else
|
|
2017
|
-
zip_reader.copy_to_writer(name, zip_writer, target_path: canonical_path)
|
|
2018
|
-
end
|
|
2019
|
-
end
|
|
2020
|
-
|
|
2021
|
-
norm_replaced.each do |norm_name, (canonical_name, content)|
|
|
2022
|
-
next if written_keys.include?(norm_name)
|
|
2023
|
-
|
|
2024
|
-
written_keys << norm_name
|
|
2025
|
-
zip_writer.add_entry(canonical_name, content)
|
|
2026
|
-
end
|
|
2027
|
-
end
|
|
2028
|
-
end
|
|
2029
|
-
|
|
2030
|
-
if password && !password.empty?
|
|
2031
|
-
buf = StringIO.new
|
|
2032
|
-
buf.binmode
|
|
2033
|
-
write_zip.call(buf)
|
|
2034
|
-
encrypted_bytes = Ooxml::Crypto.encrypt(buf.string.b, password)
|
|
2035
|
-
if dest.is_a?(String)
|
|
2036
|
-
File.binwrite(dest, encrypted_bytes)
|
|
2037
|
-
elsif dest.respond_to?(:write)
|
|
2038
|
-
dest.write(encrypted_bytes)
|
|
2039
|
-
end
|
|
2040
|
-
else
|
|
2041
|
-
write_zip.call(dest)
|
|
2042
|
-
end
|
|
2043
|
-
end
|
|
2044
|
-
|
|
2045
|
-
#: (String sst_xml, Array[untyped] new_strings) -> String
|
|
2046
|
-
def append_to_shared_strings_xml(sst_xml, new_strings)
|
|
2047
|
-
return sst_xml if new_strings.nil? || new_strings.empty?
|
|
2048
|
-
|
|
2049
|
-
sst_match = sst_xml.match(/<([a-zA-Z0-9_]+:)?sst\b([^>]*)>/)
|
|
2050
|
-
prefix_with_colon = sst_match ? (sst_match[1] || "") : ""
|
|
2051
|
-
si_tag = "#{prefix_with_colon}si"
|
|
2052
|
-
t_tag = "#{prefix_with_colon}t"
|
|
2053
|
-
|
|
2054
|
-
new_si_tags = +""
|
|
2055
|
-
new_strings.each do |str|
|
|
2056
|
-
s = str.to_s
|
|
2057
|
-
new_si_tags << "<#{si_tag}><#{t_tag}>#{Ooxml::XmlBuilder.escape(s)}</#{t_tag}></#{si_tag}>"
|
|
2058
|
-
end
|
|
2059
|
-
|
|
2060
|
-
close_tag = "</#{prefix_with_colon}sst>"
|
|
2061
|
-
sst_close = sst_xml.rindex(close_tag)
|
|
2062
|
-
updated_xml = if sst_close
|
|
2063
|
-
prefix = sst_xml[0...sst_close]
|
|
2064
|
-
suffix = sst_xml[sst_close..]
|
|
2065
|
-
"#{prefix}#{new_si_tags}#{suffix}"
|
|
2066
|
-
else
|
|
2067
|
-
self_closing = sst_xml.match(%r{<#{Regexp.escape(prefix_with_colon)}sst\b[^>]*/>})
|
|
2068
|
-
return sst_xml unless self_closing
|
|
2069
|
-
|
|
2070
|
-
sc_idx = self_closing.begin(0)
|
|
2071
|
-
sc_end = self_closing.end(0)
|
|
2072
|
-
opening = self_closing[0].sub(%r{/>\z}, ">")
|
|
2073
|
-
prefix = sst_xml[0...sc_idx]
|
|
2074
|
-
suffix = sst_xml[sc_end..]
|
|
2075
|
-
"#{prefix}#{opening}#{new_si_tags}#{close_tag}#{suffix}"
|
|
2076
|
-
end
|
|
2077
|
-
|
|
2078
|
-
updated_xml.sub(/<#{Regexp.escape(prefix_with_colon)}sst\b([^>]*)>/) do
|
|
2079
|
-
attrs = Regexp.last_match(1)
|
|
2080
|
-
if attrs =~ /\bcount="(\d+)"/
|
|
2081
|
-
old_count = Regexp.last_match(1).to_i
|
|
2082
|
-
new_count = old_count + new_strings.size
|
|
2083
|
-
attrs = attrs.sub(/\bcount="\d+"/, "count=\"#{new_count}\"")
|
|
2084
|
-
else
|
|
2085
|
-
attrs = "#{attrs} count=\"#{new_strings.size}\""
|
|
2086
|
-
end
|
|
2087
|
-
if attrs =~ /\buniqueCount="(\d+)"/
|
|
2088
|
-
old_ucount = Regexp.last_match(1).to_i
|
|
2089
|
-
new_ucount = old_ucount + new_strings.size
|
|
2090
|
-
attrs = attrs.sub(/\buniqueCount="\d+"/, "uniqueCount=\"#{new_ucount}\"")
|
|
2091
|
-
else
|
|
2092
|
-
attrs = "#{attrs} uniqueCount=\"#{new_strings.size}\""
|
|
2093
|
-
end
|
|
2094
|
-
"<#{prefix_with_colon}sst#{attrs}>"
|
|
2095
|
-
end
|
|
2096
|
-
end
|
|
2097
|
-
|
|
2098
|
-
#: (String sheet_xml, String new_sheet_data_xml) -> String
|
|
2099
|
-
def replace_sheet_data(sheet_xml, new_sheet_data_xml)
|
|
2100
|
-
orig_encoding = sheet_xml.encoding
|
|
2101
|
-
sheet_b = sheet_xml.b
|
|
2102
|
-
sd_term = sheet_b.index("sheetData")
|
|
2103
|
-
return sheet_xml unless sd_term
|
|
2104
|
-
|
|
2105
|
-
sheet_data_start = sheet_b.rindex("<", sd_term)
|
|
2106
|
-
return sheet_xml unless sheet_data_start
|
|
2107
|
-
|
|
2108
|
-
prefix_len = sd_term - (sheet_data_start + 1)
|
|
2109
|
-
tag_prefix = sheet_b.byteslice(sheet_data_start + 1, prefix_len).force_encoding(orig_encoding)
|
|
2110
|
-
|
|
2111
|
-
open_tag_end = sheet_b.index(">", sd_term)
|
|
2112
|
-
return sheet_xml unless open_tag_end
|
|
2113
|
-
|
|
2114
|
-
prefix = sheet_b.byteslice(0...sheet_data_start)
|
|
2115
|
-
suffix = if sheet_b.getbyte(open_tag_end - 1) == 47
|
|
2116
|
-
sheet_b.byteslice((open_tag_end + 1)..) || "".b
|
|
2117
|
-
else
|
|
2118
|
-
close_tag = "</#{tag_prefix}sheetData>".b
|
|
2119
|
-
close_tag_start = sheet_b.index(close_tag, open_tag_end)
|
|
2120
|
-
return sheet_xml unless close_tag_start
|
|
2121
|
-
|
|
2122
|
-
sheet_b.byteslice((close_tag_start + close_tag.bytesize)..) || "".b
|
|
2123
|
-
end
|
|
2124
|
-
|
|
2125
|
-
new_sheet_data_xml = new_sheet_data_xml.gsub(%r{</?(sheetData|row|c|v|f|is|t)\b}) { |m| m.sub(%r{(</?)}, "\\1#{tag_prefix}") } if tag_prefix && !tag_prefix.empty?
|
|
2126
|
-
|
|
2127
|
-
result = prefix << new_sheet_data_xml.b << suffix
|
|
2128
|
-
result.force_encoding(orig_encoding)
|
|
2129
|
-
end
|
|
2130
|
-
|
|
2131
|
-
#: (String sheet_xml, Array[Elements::Row] rows) -> String
|
|
2132
|
-
def update_dimension(sheet_xml, rows)
|
|
2133
|
-
return sheet_xml if rows.empty?
|
|
2134
|
-
|
|
2135
|
-
min_row = rows.first.index
|
|
2136
|
-
max_row = rows.last.index
|
|
2137
|
-
min_col = rows.map { |r| r.cells.first&.column_index }.compact.min || 0
|
|
2138
|
-
max_col = rows.map { |r| r.cells.last&.column_index }.compact.max || 0
|
|
2139
|
-
min_col_letter = Elements::Cell.column_letter(min_col)
|
|
2140
|
-
max_col_letter = Elements::Cell.column_letter(max_col)
|
|
2141
|
-
dim_ref = if min_row == max_row && min_col == max_col
|
|
2142
|
-
"#{min_col_letter}#{min_row + 1}"
|
|
2143
|
-
else
|
|
2144
|
-
"#{min_col_letter}#{min_row + 1}:#{max_col_letter}#{max_row + 1}"
|
|
2145
|
-
end
|
|
2146
|
-
|
|
2147
|
-
sheet_xml.sub(/<([a-zA-Z0-9_]+:)?dimension\b([^>]*)\bref="[^"]*"/, "<\\1dimension\\2ref=\"#{dim_ref}\"")
|
|
2148
|
-
end
|
|
2149
|
-
|
|
2150
|
-
#: (String sheet_xml, String? orig_rels_xml, Hash[String, untyped] new_hyperlinks) -> [String, String?]
|
|
2151
|
-
def update_sheet_hyperlinks(sheet_xml, orig_rels_xml, new_hyperlinks)
|
|
2152
|
-
existing_rels = []
|
|
2153
|
-
max_rid_num = 0
|
|
2154
|
-
if orig_rels_xml && !orig_rels_xml.empty?
|
|
2155
|
-
orig_rels_xml.scan(%r{<Relationship\b([^>]*)/?>}) do |m|
|
|
2156
|
-
attrs = m[0]
|
|
2157
|
-
id = attrs[/Id="([^"]*)"/, 1]
|
|
2158
|
-
type = attrs[/Type="([^"]*)"/, 1]
|
|
2159
|
-
target = attrs[/Target="([^"]*)"/, 1]
|
|
2160
|
-
target_mode = attrs[/TargetMode="([^"]*)"/, 1]
|
|
2161
|
-
if id =~ /\ArId(\d+)\z/
|
|
2162
|
-
num = Regexp.last_match(1).to_i
|
|
2163
|
-
max_rid_num = num if num > max_rid_num
|
|
2164
|
-
end
|
|
2165
|
-
existing_rels << { id: id, type: type, target: target, target_mode: target_mode } unless type == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"
|
|
2166
|
-
end
|
|
2167
|
-
end
|
|
2168
|
-
|
|
2169
|
-
sheet_rels = existing_rels.dup
|
|
2170
|
-
cur_rid = max_rid_num
|
|
2171
|
-
hl_elements = []
|
|
2172
|
-
|
|
2173
|
-
ws_prefix = sheet_xml[/<([a-zA-Z0-9_]+:)?worksheet\b/, 1] || ""
|
|
2174
|
-
|
|
2175
|
-
new_hyperlinks.each do |cell_ref, link|
|
|
2176
|
-
entry = link.is_a?(Hash) ? link.dup : { url: link.to_s }
|
|
2177
|
-
url = entry[:url]
|
|
2178
|
-
loc = entry[:location]
|
|
2179
|
-
if url&.start_with?("#")
|
|
2180
|
-
loc ||= url.delete_prefix("#")
|
|
2181
|
-
url = nil
|
|
2182
|
-
end
|
|
2183
|
-
display = entry[:display]
|
|
2184
|
-
tooltip = entry[:tooltip]
|
|
2185
|
-
|
|
2186
|
-
attrs = if url && !url.empty?
|
|
2187
|
-
cur_rid += 1
|
|
2188
|
-
rid = "rId#{cur_rid}"
|
|
2189
|
-
sheet_rels << {
|
|
2190
|
-
id: rid,
|
|
2191
|
-
type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
|
|
2192
|
-
target: url,
|
|
2193
|
-
target_mode: "External"
|
|
2194
|
-
}
|
|
2195
|
-
%(ref="#{cell_ref}" r:id="#{rid}")
|
|
2196
|
-
elsif loc && !loc.empty?
|
|
2197
|
-
%(ref="#{cell_ref}" location="#{Ooxml::XmlBuilder.escape(loc)}")
|
|
2198
|
-
else
|
|
2199
|
-
next
|
|
2200
|
-
end
|
|
2201
|
-
|
|
2202
|
-
attrs << %( display="#{Ooxml::XmlBuilder.escape(display)}") if display
|
|
2203
|
-
attrs << %( tooltip="#{Ooxml::XmlBuilder.escape(tooltip)}") if tooltip
|
|
2204
|
-
hl_elements << "<#{ws_prefix}hyperlink #{attrs}/>"
|
|
2205
|
-
end
|
|
2206
|
-
|
|
2207
|
-
updated_sheet_xml = sheet_xml.dup
|
|
2208
|
-
root_tag = updated_sheet_xml[/\A\s*(?:<\?xml[^>]*\?>\s*)?<([a-zA-Z0-9_]+:)?worksheet\b[^>]*/, 0]
|
|
2209
|
-
updated_sheet_xml.sub!(/<([a-zA-Z0-9_]+:)?worksheet\b/, '\0 xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"') if hl_elements.any? && (root_tag.nil? || !root_tag.match?(/\bxmlns:r\s*=/))
|
|
2210
|
-
|
|
2211
|
-
new_hyperlinks_xml = hl_elements.empty? ? "" : "<#{ws_prefix}hyperlinks>#{hl_elements.join}</#{ws_prefix}hyperlinks>"
|
|
2212
|
-
|
|
2213
|
-
if updated_sheet_xml =~ /<([a-zA-Z0-9_]+:)?hyperlinks\b/
|
|
2214
|
-
updated_sheet_xml.sub!(%r{<(([a-zA-Z0-9_]+:)?hyperlinks)\b(?:[^>]*/>|[^>]*>.*?</\1>)}m) { new_hyperlinks_xml }
|
|
2215
|
-
elsif hl_elements.any?
|
|
2216
|
-
search_start = 0
|
|
2217
|
-
%w[sheetData customSheetViews mergeCells conditionalFormatting dataValidations].each do |tag|
|
|
2218
|
-
pattern = if ws_prefix.empty?
|
|
2219
|
-
%r{</#{tag}>|<#{tag}\b[^>]*/\s*>}
|
|
2220
|
-
else
|
|
2221
|
-
%r{</#{Regexp.escape(ws_prefix)}#{tag}>|<#{Regexp.escape(ws_prefix)}#{tag}\b[^>]*/\s*>}
|
|
2222
|
-
end
|
|
2223
|
-
if (m = updated_sheet_xml.match(pattern))
|
|
2224
|
-
end_pos = m.end(0)
|
|
2225
|
-
search_start = end_pos if end_pos > search_start
|
|
2226
|
-
end
|
|
2227
|
-
end
|
|
2228
|
-
|
|
2229
|
-
tags_sub = "printOptions|pageMargins|pageSetup|headerFooter|rowBreaks|colBreaks|customProperties|cellWatches|ignoredErrors|smartTags|drawing|legacyDrawing|legacyDrawingHF|picture|oleObjects|controls|webPublishItems|tableParts|extLst"
|
|
2230
|
-
insert_pattern = if ws_prefix.empty?
|
|
2231
|
-
%r{<(?:#{tags_sub})\b|</worksheet>}
|
|
2232
|
-
else
|
|
2233
|
-
%r{<#{Regexp.escape(ws_prefix)}(?:#{tags_sub})\b|</#{Regexp.escape(ws_prefix)}worksheet>}
|
|
2234
|
-
end
|
|
2235
|
-
match = updated_sheet_xml.match(insert_pattern, search_start)
|
|
2236
|
-
if match
|
|
2237
|
-
updated_sheet_xml.insert(match.begin(0), new_hyperlinks_xml)
|
|
2238
|
-
else
|
|
2239
|
-
updated_sheet_xml << new_hyperlinks_xml
|
|
2240
|
-
end
|
|
2241
|
-
end
|
|
2242
|
-
|
|
2243
|
-
updated_rels_xml = if sheet_rels.empty? && (orig_rels_xml.nil? || orig_rels_xml.empty?)
|
|
2244
|
-
nil
|
|
2245
|
-
else
|
|
2246
|
-
io = StringIO.new
|
|
2247
|
-
b = Ooxml::XmlBuilder.new(io)
|
|
2248
|
-
b.declaration
|
|
2249
|
-
b.open_tag("Relationships", { xmlns: "http://schemas.openxmlformats.org/package/2006/relationships" })
|
|
2250
|
-
sheet_rels.each do |rel|
|
|
2251
|
-
rel_attrs = { Id: rel[:id], Type: rel[:type], Target: rel[:target] }
|
|
2252
|
-
rel_attrs[:TargetMode] = rel[:target_mode] if rel[:target_mode]
|
|
2253
|
-
b.empty_tag("Relationship", rel_attrs)
|
|
2254
|
-
end
|
|
2255
|
-
b.close_tag("Relationships")
|
|
2256
|
-
io.string
|
|
2257
|
-
end
|
|
2258
|
-
|
|
2259
|
-
[updated_sheet_xml, updated_rels_xml]
|
|
2260
|
-
end
|
|
2261
|
-
|
|
2262
|
-
#: (String sheet_xml, String _rels_path, String? orig_rels_xml, Array[Hash[Symbol, untyped]] new_comments, Ooxml::ZipReader zip_reader, Integer sheet_idx, String entry_name, Hash[String, String] replaced_entries) -> [String, String?]
|
|
2263
|
-
def update_sheet_comments(sheet_xml, _rels_path, orig_rels_xml, new_comments, zip_reader, sheet_idx, entry_name, replaced_entries)
|
|
2264
|
-
existing_rels = []
|
|
2265
|
-
max_rid_num = 0
|
|
2266
|
-
if orig_rels_xml && !orig_rels_xml.empty?
|
|
2267
|
-
orig_rels_xml.scan(%r{<Relationship\b([^>]*)/?>}) do |m|
|
|
2268
|
-
attrs = m[0]
|
|
2269
|
-
id = attrs[/Id="([^"]*)"/, 1]
|
|
2270
|
-
type = attrs[/Type="([^"]*)"/, 1]
|
|
2271
|
-
target = attrs[/Target="([^"]*)"/, 1]
|
|
2272
|
-
target_mode = attrs[/TargetMode="([^"]*)"/, 1]
|
|
2273
|
-
if id =~ /\ArId(\d+)\z/
|
|
2274
|
-
num = Regexp.last_match(1).to_i
|
|
2275
|
-
max_rid_num = num if num > max_rid_num
|
|
2276
|
-
end
|
|
2277
|
-
existing_rels << { id: id, type: type, target: target, target_mode: target_mode }
|
|
2278
|
-
end
|
|
2279
|
-
end
|
|
2280
|
-
|
|
2281
|
-
comments_rel = existing_rels.find { |r| r[:type]&.end_with?("/comments") }
|
|
2282
|
-
vml_rel = existing_rels.find { |r| r[:type]&.end_with?("/vmlDrawing") }
|
|
2283
|
-
|
|
2284
|
-
writer = Ooxml::Writer.new
|
|
2285
|
-
new_comments.each do |c|
|
|
2286
|
-
writer.add_comment(c[:cell] || c[:ref], c[:text], author: c[:author] || "Author")
|
|
2287
|
-
end
|
|
2288
|
-
comments_xml = writer.send(:generate_comments_xml, writer.comments)
|
|
2289
|
-
vml_xml = writer.send(:generate_vml_drawing_xml, writer.comments)
|
|
2290
|
-
|
|
2291
|
-
updated_sheet_xml = sheet_xml.dup
|
|
2292
|
-
|
|
2293
|
-
if comments_rel
|
|
2294
|
-
base_dir = File.dirname(entry_name)
|
|
2295
|
-
comments_path = resolve_relative_path(base_dir, comments_rel[:target])
|
|
2296
|
-
replaced_entries[comments_path] = comments_xml
|
|
2297
|
-
if vml_rel
|
|
2298
|
-
vml_path = resolve_relative_path(base_dir, vml_rel[:target])
|
|
2299
|
-
replaced_entries[vml_path] = vml_xml
|
|
2300
|
-
end
|
|
2301
|
-
elsif new_comments.any?
|
|
2302
|
-
existing_comment_count = zip_reader.entry_names.count { |n| n =~ %r{\Axl/comments\d+\.xml\z} }
|
|
2303
|
-
comment_file_num = existing_comment_count + sheet_idx + 1
|
|
2304
|
-
comments_path = "xl/comments#{comment_file_num}.xml"
|
|
2305
|
-
vml_path = "xl/drawings/vmlDrawing#{comment_file_num}.vml"
|
|
2306
|
-
replaced_entries[comments_path] = comments_xml
|
|
2307
|
-
replaced_entries[vml_path] = vml_xml
|
|
2308
|
-
|
|
2309
|
-
max_rid_num += 1
|
|
2310
|
-
c_rid = "rId#{max_rid_num}"
|
|
2311
|
-
existing_rels << {
|
|
2312
|
-
id: c_rid,
|
|
2313
|
-
type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
|
|
2314
|
-
target: "../comments#{comment_file_num}.xml"
|
|
2315
|
-
}
|
|
2316
|
-
|
|
2317
|
-
max_rid_num += 1
|
|
2318
|
-
vml_rid = "rId#{max_rid_num}"
|
|
2319
|
-
existing_rels << {
|
|
2320
|
-
id: vml_rid,
|
|
2321
|
-
type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing",
|
|
2322
|
-
target: "../drawings/vmlDrawing#{comment_file_num}.vml"
|
|
2323
|
-
}
|
|
2324
|
-
|
|
2325
|
-
ws_prefix = updated_sheet_xml[/<([a-zA-Z0-9_]+:)?worksheet\b/, 1] || ""
|
|
2326
|
-
legacy_pattern = ws_prefix.empty? ? /<legacyDrawing\b/ : /<#{Regexp.escape(ws_prefix)}legacyDrawing\b/
|
|
2327
|
-
unless updated_sheet_xml =~ legacy_pattern
|
|
2328
|
-
legacy_tag = %(<#{ws_prefix}legacyDrawing r:id="#{vml_rid}"/>)
|
|
2329
|
-
search_start = 0
|
|
2330
|
-
%w[sheetData customSheetViews mergeCells conditionalFormatting dataValidations hyperlinks pageMargins pageSetup].each do |tag|
|
|
2331
|
-
pattern = if ws_prefix.empty?
|
|
2332
|
-
%r{</#{tag}>|<#{tag}\b[^>]*/\s*>}
|
|
2333
|
-
else
|
|
2334
|
-
%r{</#{Regexp.escape(ws_prefix)}#{tag}>|<#{Regexp.escape(ws_prefix)}#{tag}\b[^>]*/\s*>}
|
|
2335
|
-
end
|
|
2336
|
-
if (m = updated_sheet_xml.match(pattern))
|
|
2337
|
-
end_pos = m.end(0)
|
|
2338
|
-
search_start = end_pos if end_pos > search_start
|
|
2339
|
-
end
|
|
2340
|
-
end
|
|
2341
|
-
|
|
2342
|
-
tags_sub = "legacyDrawingHF|picture|oleObjects|controls|webPublishItems|tableParts|extLst"
|
|
2343
|
-
insert_pattern = if ws_prefix.empty?
|
|
2344
|
-
%r{<(?:#{tags_sub})\b|</worksheet>}
|
|
2345
|
-
else
|
|
2346
|
-
%r{<#{Regexp.escape(ws_prefix)}(?:#{tags_sub})\b|</#{Regexp.escape(ws_prefix)}worksheet>}
|
|
2347
|
-
end
|
|
2348
|
-
match = updated_sheet_xml.match(insert_pattern, search_start)
|
|
2349
|
-
if match
|
|
2350
|
-
updated_sheet_xml.insert(match.begin(0), legacy_tag)
|
|
2351
|
-
else
|
|
2352
|
-
updated_sheet_xml << legacy_tag
|
|
2353
|
-
end
|
|
2354
|
-
end
|
|
2355
|
-
|
|
2356
|
-
root_tag = updated_sheet_xml[/\A\s*(?:<\?xml[^>]*\?>\s*)?<([a-zA-Z0-9_]+:)?worksheet\b[^>]*/, 0]
|
|
2357
|
-
updated_sheet_xml.sub!(/<([a-zA-Z0-9_]+:)?worksheet\b/, '\0 xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"') if root_tag.nil? || !root_tag.match?(/\bxmlns:r\s*=/)
|
|
2358
|
-
|
|
2359
|
-
ct_xml = replaced_entries["[Content_Types].xml"] || zip_reader.read_entry("[Content_Types].xml")
|
|
2360
|
-
if ct_xml && !ct_xml.include?("comments#{comment_file_num}.xml")
|
|
2361
|
-
override_tag = %(<Override PartName="/#{comments_path}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml"/>)
|
|
2362
|
-
ct_xml = ct_xml.sub(%r{</Types>}, "#{override_tag}</Types>")
|
|
2363
|
-
unless ct_xml.include?('Extension="vml"')
|
|
2364
|
-
default_vml = %(<Default Extension="vml" ContentType="application/vnd.openxmlformats-officedocument.vmlDrawing"/>)
|
|
2365
|
-
ct_xml = ct_xml.sub(%r{</Types>}, "#{default_vml}</Types>")
|
|
2366
|
-
end
|
|
2367
|
-
replaced_entries["[Content_Types].xml"] = ct_xml
|
|
2368
|
-
end
|
|
2369
|
-
end
|
|
2370
|
-
|
|
2371
|
-
io = StringIO.new
|
|
2372
|
-
b = Ooxml::XmlBuilder.new(io)
|
|
2373
|
-
b.declaration
|
|
2374
|
-
b.open_tag("Relationships", { xmlns: "http://schemas.openxmlformats.org/package/2006/relationships" })
|
|
2375
|
-
existing_rels.each do |rel|
|
|
2376
|
-
rel_attrs = { Id: rel[:id], Type: rel[:type], Target: rel[:target] }
|
|
2377
|
-
rel_attrs[:TargetMode] = rel[:target_mode] if rel[:target_mode]
|
|
2378
|
-
b.empty_tag("Relationship", rel_attrs)
|
|
2379
|
-
end
|
|
2380
|
-
b.close_tag("Relationships")
|
|
2381
|
-
|
|
2382
|
-
[updated_sheet_xml, io.string]
|
|
2383
|
-
end
|
|
2384
|
-
|
|
2385
|
-
#: (Array[Elements::Row] rows, Array[untyped] shared_strings, Hash[untyped, Integer] sst_index, ?use_sst: bool, ?date1904: bool) -> String
|
|
2386
|
-
def serialize_sheet_data_xml(rows, shared_strings, sst_index, use_sst: true, date1904: false)
|
|
2387
|
-
io = StringIO.new
|
|
2388
|
-
io.write("<sheetData>")
|
|
2389
|
-
ws = Ooxml::WorksheetWriter.new(io, date1904: date1904)
|
|
2390
|
-
ws.instance_variable_set(:@started, true)
|
|
2391
|
-
|
|
2392
|
-
rows.each do |row|
|
|
2393
|
-
attrs = {}
|
|
2394
|
-
attrs[:height] = row.height if row.height
|
|
2395
|
-
attrs[:hidden] = true if row.hidden
|
|
2396
|
-
attrs[:custom_height] = true if row.custom_height
|
|
2397
|
-
attrs[:outline_level] = row.outline_level if row.outline_level
|
|
2398
|
-
|
|
2399
|
-
if use_sst
|
|
2400
|
-
row.cells.each do |cell|
|
|
2401
|
-
val = cell.value
|
|
2402
|
-
next unless val.is_a?(String) || val.is_a?(Elements::RichText)
|
|
2403
|
-
next if sst_index.key?(val)
|
|
2404
|
-
|
|
2405
|
-
shared_strings << val
|
|
2406
|
-
sst_index[val] = shared_strings.size - 1
|
|
2407
|
-
end
|
|
2408
|
-
end
|
|
2409
|
-
|
|
2410
|
-
ws.write_row(
|
|
2411
|
-
row.index,
|
|
2412
|
-
row.cells,
|
|
2413
|
-
attrs: attrs,
|
|
2414
|
-
unmapped: row.unmapped_data || [],
|
|
2415
|
-
sst_index: use_sst ? sst_index : nil
|
|
2416
|
-
)
|
|
2417
|
-
end
|
|
2418
|
-
|
|
2419
|
-
buf = ws.instance_variable_get(:@row_buffer)
|
|
2420
|
-
if buf && !buf.empty?
|
|
2421
|
-
io.write(buf)
|
|
2422
|
-
buf.clear
|
|
2423
|
-
end
|
|
2424
|
-
io.write("</sheetData>")
|
|
2425
|
-
io.string
|
|
2426
|
-
end
|
|
2427
|
-
end
|
|
2428
|
-
|
|
2429
|
-
# Builds a raw cell hash from a value for streaming writes.
|
|
2430
|
-
#
|
|
2431
|
-
# @param row_index [Integer] 0-based row index.
|
|
2432
|
-
# @param col_index [Integer] 0-based column index.
|
|
2433
|
-
# @param value [Object] Cell value.
|
|
2434
|
-
# @param sst [Array<String>] Shared strings array.
|
|
2435
|
-
# @param sst_index [Hash{String => Integer}] Shared strings index mapping.
|
|
2436
|
-
# @return [Hash{Symbol => Object}] Raw cell hash.
|
|
2437
|
-
# @api public
|
|
2438
|
-
#: (Integer row_index, Integer col_index, untyped value, Array[String] sst, Hash[String, Integer] sst_index, ?date1904: bool) -> Hash[Symbol, untyped]
|
|
2439
|
-
def self.build_raw_cell_from_value(row_index, col_index, value, sst, sst_index, date1904: false)
|
|
2440
|
-
# simplecov:disable
|
|
2441
|
-
# Edge case / untested delegation block
|
|
2442
|
-
ref = "#{Elements::Cell.column_letter(col_index)}#{row_index + 1}"
|
|
2443
|
-
result = { ref: ref }
|
|
2444
|
-
|
|
2445
|
-
case value
|
|
2446
|
-
when Elements::Formula
|
|
2447
|
-
result[:formula] = value.expression
|
|
2448
|
-
result[:formula_type] = value.type if value.type
|
|
2449
|
-
result[:formula_ref] = value.ref if value.ref
|
|
2450
|
-
result[:formula_si] = value.shared_index if value.shared_index
|
|
2451
|
-
result[:formula_ca] = true if value.calculate_always
|
|
2452
|
-
unless value.cached_value.nil?
|
|
2453
|
-
cv = value.cached_value
|
|
2454
|
-
result[:value] = cv
|
|
2455
|
-
case cv
|
|
2456
|
-
when true, false
|
|
2457
|
-
result[:type] = "b"
|
|
2458
|
-
when Xlsxrb::Elements::CellError
|
|
2459
|
-
result[:type] = "e"
|
|
2460
|
-
result[:value] = cv.code
|
|
2461
|
-
end
|
|
2462
|
-
end
|
|
2463
|
-
when Hash
|
|
2464
|
-
if value.key?(:formula) || value.key?(:expression) || (value[:type]&.to_sym == :shared && (value.key?(:shared_index) || value.key?(:si)))
|
|
2465
|
-
result[:formula] = value[:formula] || value[:expression]
|
|
2466
|
-
result[:formula_type] = value[:type] || (:shared if value.key?(:shared_index) || value.key?(:si))
|
|
2467
|
-
result[:formula_ref] = value[:ref] if value[:ref]
|
|
2468
|
-
si = value[:shared_index] || value[:si]
|
|
2469
|
-
result[:formula_si] = si if si
|
|
2470
|
-
result[:formula_ca] = true if value[:calculate_always]
|
|
2471
|
-
cv = value.key?(:value) ? value[:value] : value[:cached_value]
|
|
2472
|
-
unless cv.nil?
|
|
2473
|
-
result[:value] = cv
|
|
2474
|
-
case cv
|
|
2475
|
-
when true, false
|
|
2476
|
-
result[:type] = "b"
|
|
2477
|
-
when Xlsxrb::Elements::CellError
|
|
2478
|
-
result[:type] = "e"
|
|
2479
|
-
result[:value] = cv.code
|
|
2480
|
-
end
|
|
2481
|
-
end
|
|
2482
|
-
end
|
|
2483
|
-
when String, Xlsxrb::Elements::RichText
|
|
2484
|
-
idx = sst_index[value] ||= begin
|
|
2485
|
-
sst << value
|
|
2486
|
-
sst.size - 1
|
|
2487
|
-
end
|
|
2488
|
-
result[:value] = idx
|
|
2489
|
-
result[:type] = "s"
|
|
2490
|
-
when true, false
|
|
2491
|
-
result[:value] = value
|
|
2492
|
-
result[:type] = "b"
|
|
2493
|
-
when Integer, Float
|
|
2494
|
-
result[:value] = value
|
|
2495
|
-
when Xlsxrb::Elements::CellError
|
|
2496
|
-
result[:value] = value.code
|
|
2497
|
-
result[:type] = "e"
|
|
2498
|
-
when Date
|
|
2499
|
-
result[:value] = Xlsxrb::Ooxml::Utils.date_to_serial(value, date1904: date1904)
|
|
2500
|
-
when Time
|
|
2501
|
-
result[:value] = Xlsxrb::Ooxml::Utils.datetime_to_serial(value, date1904: date1904)
|
|
2502
|
-
# simplecov:enable
|
|
2503
|
-
when NilClass
|
|
2504
|
-
# empty cell
|
|
2505
|
-
end
|
|
2506
|
-
|
|
2507
|
-
# simplecov:disable
|
|
2508
|
-
# Edge case / untested delegation block
|
|
2509
|
-
result
|
|
2510
|
-
# simplecov:enable
|
|
2511
2634
|
end
|
|
2512
2635
|
end
|