class Xlsxrb::Ooxml::WorksheetParser
Streaming parser for xl/worksheets/sheetN.xml. Uses a fast string-scanning approach for row/cell extraction, falling back to REXML SAX only for column definitions and unmapped data.
Constants
- ATTR_R
- ATTR_S
- ATTR_T
- CELL_FAST_RE
-
Captures r, s, and t directly when they appear in the order Excel and xlsxrb write them (groups 1 to 3). Any other attribute set or order falls back to capturing the raw attribute string (group 4, or group 9 for a self-closing cell) for ATTR_* lookups.
- CELL_GENERIC_RE
- COL_LETTERS
- COL_MAP
- EMPTY_ARRAY
- EMPTY_BINARY
- EMPTY_HASH
- MAX_ROW_NUMBER
-
Excel’s last row. A larger row number is not a worksheet row, and an unbounded one would be built digit by digit into an arbitrarily large Integer.
- ROW_ATTR_START_BYTES
- TAG_DELIM_BYTES
Public Class Methods
(String str) → String
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 648 def self.decode_xml_entities(str) XmlBuilder.unescape(str) end
SECURITY NOTE: Decodes only standard predefined XML entities in a single pass. This completely prevents “Billion Laughs” attacks (exponential entity expansion) because it avoids recursive expansion and ignores custom entities entirely.
(untyped xml_string, ?shared_strings: untyped, ?part_name: untyped) ?{ (?) → untyped } → untyped
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 85 def self.each_event(xml_string, shared_strings: [], part_name: "xl/worksheets/sheet1.xml", &block) return enum_for(:each_event, xml_string, shared_strings: shared_strings, part_name: part_name) unless block return if xml_string.nil? || xml_string.empty? # 1. Parse and yield column events if xml_string.include?("<cols") listener = ColumnsListener.new XmlParser.parse(xml_string, listener) listener.columns.each do |col| block.call(Event.new( type: :column, args: [col[:min], col[:max], col[:width], col[:hidden], col[:custom_width], col[:outline_level]], source: { part: part_name } )) end end # 2. Parse and yield row/cell events fast_scan_events(xml_string, shared_strings, part_name, &block) # 3. Parse and yield hyperlink events parse_hyperlinks(xml_string).each do |hl| block.call(Event.new( type: :hyperlink, args: [hl[:ref], hl[:rid], hl[:display], hl[:tooltip], hl[:location]], source: { part: part_name, cell: hl[:ref] } )) end end
Yields Event objects for columns, rows, cells, and hyperlinks.
(untyped xml_source, ?shared_strings: untyped, ?part_name: untyped, ?styles: untyped, ?date1904: untyped, ?trim_empty_rows: untyped, ?pad_empty_rows: untyped, ?pad_empty_cells: untyped) ?{ (?) → untyped } → untyped
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 32 def self.each_row(xml_source, shared_strings: [], part_name: "xl/worksheets/sheet1.xml", styles: nil, date1904: false, trim_empty_rows: false, pad_empty_rows: false, pad_empty_cells: false, &block) return enum_for(:each_row, xml_source, shared_strings: shared_strings, part_name: part_name, styles: styles, date1904: date1904, trim_empty_rows: trim_empty_rows, pad_empty_rows: pad_empty_rows, pad_empty_cells: pad_empty_cells) unless block return if xml_source.nil? || (xml_source.respond_to?(:empty?) && xml_source.empty?) row_consumer = if trim_empty_rows pending_empty = [] lambda do |row| if row.empty? pending_empty << row else pending_empty.each(&block) pending_empty.clear block.call(row) end end else block end if pad_empty_rows current_expected_idx = 0 inner_consumer = row_consumer row_consumer = lambda do |row| while current_expected_idx < row.index empty_row = StreamRow.fast_create( current_expected_idx, "".b, 0, 0, shared_strings, "", nil, false, false, nil, nil, styles, date1904, false, pad_empty_cells ) inner_consumer.call(empty_row) current_expected_idx += 1 end inner_consumer.call(row) current_expected_idx = row.index + 1 end end if xml_source.is_a?(String) fast_scan_rows_direct(xml_source, shared_strings, part_name, styles, date1904, pad_empty_cells, &row_consumer) else scan_rows_stream(xml_source, shared_strings, part_name, styles, date1904, pad_empty_cells, &row_consumer) end end
Streaming parse: yields one raw row hash at a time.
(untyped xml, untyped from, untyped to, untyped shared_strings, untyped row_source, ?untyped _prefix, ?untyped styles, ?untyped date1904, ?untyped shared_formulas) ?{ (?) → untyped } → untyped
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 1270 def self.fast_scan_cells_direct(xml, from, to, shared_strings, row_source, _prefix = "", styles = nil, date1904 = false, shared_formulas = nil, &) # rubocop:enable Style/OptionalBooleanParameter chunk = scrub_row(xml.byteslice(from, to - from)) verify_cells_closed!(chunk) row_idx = row_source.is_a?(Hash) ? row_source[:row] : row_source col_idx = 0 matched_any = false chunk.scan(CELL_FAST_RE) do |r, s, t, attrs_str, f_attrs, f, v, is, self_attrs| matched_any = true unless r raw_attrs = attrs_str || self_attrs || "" r = raw_attrs[ATTR_R, 1] s = raw_attrs.include?('s="') ? raw_attrs[ATTR_S, 1] : nil t = raw_attrs.include?('t="') ? raw_attrs[ATTR_T, 1] : nil end style_idx = s&.to_i ref = r c_idx = resolve_cell_col_index(ref, col_idx) col_idx = c_idx + 1 v = utf8!(strip_ws(v)) if v f = utf8!(strip_ws(f)) if f val = resolve_cell_value(t, v, is, shared_strings) raw_val = if is extract_inline_text(is, 0, is.bytesize) elsif v normalize_text(v) end formula_val = if f_attrs cell_ref = ref || "#{COL_LETTERS[c_idx]}#{row_idx + 1}" build_formula_from_attrs(f_attrs, f, cell_ref, shared_formulas) elsif f expr = normalize_text(f) expr.empty? ? nil : expr end fmt_code = NumberFormatter.format_code_for(style_idx, styles) if styles && style_idx cell = Elements::Cell.fast_create(row_idx, c_idx, val, style_idx, formula_val, raw_val, fmt_code, date1904) yield cell end return if matched_any || (!chunk.include?("<c") && !chunk.include?(":c")) # Fallback for non-standard attribute ordering chunk.scan(CELL_GENERIC_RE) do |attrs, f_attrs, f, v, is| r = attrs[ATTR_R, 1] t = attrs[ATTR_T, 1] s = attrs[ATTR_S, 1] c_idx = resolve_cell_col_index(r, col_idx) col_idx = c_idx + 1 v = utf8!(strip_ws(v)) if v f = utf8!(strip_ws(f)) if f val = resolve_cell_value(t, v, is, shared_strings) raw_val = if is extract_inline_text(is, 0, is.bytesize) elsif v normalize_text(v) end style_idx = s&.to_i formula_val = if f_attrs cell_ref = r || "#{COL_LETTERS[c_idx]}#{row_idx + 1}" build_formula_from_attrs(f_attrs, f, cell_ref, shared_formulas) elsif f expr = normalize_text(f) expr.empty? ? nil : expr end fmt_code = NumberFormatter.format_code_for(style_idx, styles) if styles && style_idx cell = Elements::Cell.fast_create(row_idx, c_idx, val, style_idx, formula_val, raw_val, fmt_code, date1904) yield cell end end
rubocop:disable Style/OptionalBooleanParameter
(String xml, Integer from, Integer to, Array[String | Elements::RichText | untyped] shared_strings, ?untyped styles, ?bool date1904, ?type_cast: bool) → Array[untyped]
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 1350 def self.fast_scan_row_values(xml, from, to, shared_strings, styles = nil, date1904 = false, type_cast: false) # rubocop:enable Style/OptionalBooleanParameter chunk = xml.byteslice(from, to - from) return [] if chunk.nil? || chunk.empty? chunk = scrub_row(chunk) verify_cells_closed!(chunk) col_idx = 0 matched_any = false row_values = [] chunk.scan(CELL_FAST_RE) do |r, s_val, t, attrs_str, _f_attrs, _f, v, is, self_attrs| matched_any = true unless r raw_attrs = attrs_str || self_attrs || "" r = raw_attrs[ATTR_R, 1] s_val = raw_attrs.include?('s="') ? raw_attrs[ATTR_S, 1] : nil t = raw_attrs.include?('t="') ? raw_attrs[ATTR_T, 1] : nil end ref = r c_idx = resolve_cell_col_index(ref, col_idx) col_idx = c_idx + 1 v = v.strip if v val = resolve_cell_value(t, v, is, shared_strings) if type_cast && val.is_a?(Numeric) && s_val && styles fmt_type = NumberFormatter.format_type_for(s_val.to_i, styles) begin case fmt_type when :date val = Utils.serial_to_date(val, date1904: date1904) when :datetime, :time val = Utils.serial_to_datetime(val, date1904: date1904) end rescue StandardError # Keep numeric value on conversion failure end end row_values[c_idx] = val end return row_values if matched_any || (!chunk.include?("<c") && !chunk.include?(":c")) # Fallback for non-standard attribute ordering chunk.scan(CELL_GENERIC_RE) do |attrs, _f_attrs, _f, v, is| r = attrs[ATTR_R, 1] t = attrs[ATTR_T, 1] s = attrs[ATTR_S, 1] c_idx = resolve_cell_col_index(r, col_idx) col_idx = c_idx + 1 v = v.strip if v val = resolve_cell_value(t, v, is, shared_strings) if type_cast && val.is_a?(Numeric) && s && styles fmt_type = NumberFormatter.format_type_for(s.to_i, styles) begin case fmt_type when :date val = Utils.serial_to_date(val, date1904: date1904) when :datetime, :time val = Utils.serial_to_datetime(val, date1904: date1904) end rescue StandardError # Keep numeric value on conversion failure end end row_values[c_idx] = val end row_values end
rubocop:disable Style/OptionalBooleanParameter
(String str) → String
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 653 def self.normalize_text(str) utf8 = str.encoding == Encoding::BINARY ? str.dup.force_encoding(Encoding::UTF_8) : str utf8 = utf8.scrub unless utf8.valid_encoding? s = utf8.include?("<![CDATA[") ? decode_text_with_cdata(utf8) : decode_xml_entities(utf8) s = s.gsub("\r\n", "\n").tr("\r", "\n") if s.include?("\r") s end
(String raw) → (Integer | Float)?
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 614 def self.numeric_cell_value(raw) text = strip_ws(raw) return nil if text.empty? raise(ParseError, "invalid numeric cell value: #{text[0, 40].inspect}") unless text.bytesize <= MAX_NUMERIC_TEXT_BYTES && text.match?(STRICT_NUMERIC_RE) Integer(text, 10, exception: false) || Float(text, exception: false) || raise(ParseError, "invalid numeric cell value: #{text[0, 40].inspect}") end
Converts the text of a numeric cell (<c t=“n”>) into an Integer or Float. An empty <v></v> carries no value and yields nil. Text that is not an xsd:double (e.g. “abc”) cannot come from a conforming producer and raises ParseError instead of silently becoming 0.
(untyped xml_string, ?shared_strings: untyped, ?styles: untyped) → untyped
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 23 def self.parse(xml_string, shared_strings: [], styles: nil) return [] if xml_string.nil? || xml_string.empty? rows = [] each_row(xml_string, shared_strings: shared_strings, styles: styles) { |row| rows << row } rows end
Parses all rows from a worksheet XML string. Returns an Array of raw row hashes:
{ index:, cells: [{ ref:, type:, style_index:, value:, formula: }], attrs:, unmapped: }
(untyped xml_string, ?untyped _part_name) → untyped
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 75 def self.parse_columns(xml_string, _part_name = "xl/worksheets/sheet1.xml") return [] if xml_string.nil? || xml_string.empty? return [] unless xml_string.include?("<cols") listener = ColumnsListener.new XmlParser.parse(xml_string, listener) listener.columns end
Parses column definitions (<cols>) from a worksheet.
(String?) → Array[Hash[Symbol, untyped]]
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 121 def self.parse_hyperlinks(xml_string) return [] if xml_string.nil? || xml_string.empty? return [] unless xml_string.include?("hyperlink") xml = xml_string.b hpos_term = xml.index("hyperlinks") return [] unless hpos_term hpos = xml.rindex("<", hpos_term) return [] unless hpos h_end_term = xml.index("/hyperlinks", hpos) h_end = h_end_term ? xml.index(">", h_end_term) : xml.size h_end ||= xml.size links = [] pos = hpos while pos < h_end hl_start_term = xml.index("hyperlink", pos) break unless hl_start_term && hl_start_term < h_end hl_start = xml.rindex("<", hl_start_term) break unless hl_start && hl_start < h_end hl_tag_end = xml.index(">", hl_start + 1) break unless hl_tag_end # "hyperlink" in text or a comment rather than in a tag: the tag found before it has # already ended. Continue after the word, so that the position always advances. if hl_tag_end < hl_start_term pos = hl_start_term + 9 next end hl_tag = xml.byteslice(hl_start, hl_tag_end - hl_start) ref = tag_attr(hl_tag, ' ref="') rid = tag_attr(hl_tag, ' r:id="') || tag_attr(hl_tag, ' id="') || hl_tag[/(?:[a-zA-Z0-9_]+:)?id="([^"]+)"/, 1] display = decoded_attr(hl_tag, ' display="') tooltip = decoded_attr(hl_tag, ' tooltip="') location = decoded_attr(hl_tag, ' location="') if ref entry = { ref: ref } entry[:rid] = rid if rid entry[:display] = display if display entry[:tooltip] = tooltip if tooltip entry[:location] = location if location links << entry end pos = hl_tag_end + 1 end links end
Parses all hyperlink elements from worksheet XML.
@param xml_string [String, nil] @return [Array<Hash[Symbol, untyped]>] @api public
(String? type, String? raw_value, String? is_xml, Array[String | Elements::RichText | untyped] shared_strings) → untyped
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 568 def self.resolve_cell_value(type, raw_value, is_xml, shared_strings) case type when "s" raw_value ? shared_string_at(shared_strings, raw_value) : nil when "b" if raw_value v = strip_ws(raw_value) v == "1" || v.casecmp?("true") end when "inlineStr", "str", "e" if is_xml extract_inline_text(is_xml, 0, is_xml.bytesize) elsif raw_value normalize_text(raw_value) end when "d" raw_value && normalize_text(raw_value) when "n" raw_value ? numeric_cell_value(raw_value) : nil else if raw_value text = strip_ws(raw_value) return nil if text.empty? if text.bytesize <= MAX_NUMERIC_TEXT_BYTES && text.match?(STRICT_NUMERIC_RE) Integer(text, 10, exception: false) || Float(text, exception: false) || normalize_text(raw_value) else normalize_text(raw_value) end end end end
Resolves a cell value from its type attribute and parsed XML content (<v> or <is>). Consolidates parsing across fast-scan direct, row values, events, and listener paths.
(String str) → String
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 548 def self.strip_ws(str) first = str.getbyte(0) return str if first.nil? || (first > 32 && str.getbyte(-1) > 32) str.strip end
Returns str without leading and trailing whitespace, allocating a new String only when there is whitespace to remove (cell values rarely have any).
(String? str) → String?
Source
# File lib/xlsxrb/ooxml/worksheet_parser.rb, line 558 def self.utf8!(str) return nil unless str str.force_encoding(Encoding::UTF_8) str.valid_encoding? ? str : str.scrub end
Retags a String captured from the binary scan buffer as UTF-8 in place, without copying. Only for Strings the caller has just created (e.g. regex captures).