module Xlsxrb
Modern, streaming-capable, low-memory XLSX reading and writing library for Ruby.
Provides high-level facade methods ({Xlsxrb.read}, {Xlsxrb.write}, {Xlsxrb.build}, {Xlsxrb.load}) with full ECMA-376 OpenXML compliance, MS-OFFCRYPTO password protection, and zero core dependencies.
Constants
- DEFAULT_COMPRESSION_LEVEL
-
ZIP deflate level used when no compression_level is given. See docs/adr/0009-default-zip-compression-level.md.
- MAX_COLUMN
-
Maximum number of columns supported by Excel / OpenXML.
- MAX_REFS_PER_VALIDATION
-
Maximum number of individual cell/range references allowed in a single data validation element by Excel.
- MAX_ROW
-
Maximum number of rows supported by Excel / OpenXML.
- VERSION
Public Class Methods
(String expression, ?ref: String?, ?cached_value: (String | Numeric | bool | Elements::CellError | nil), **untyped attrs) → Elements::Formula
Source
# File lib/xlsxrb.rb, line 277 def self.array_formula(expression, ref: nil, cached_value: nil, **attrs) Elements::Formula.new( expression: expression, cached_value: cached_value, type: :array, ref: ref, calculate_always: cached_value.nil? || nil, **attrs ) end
Creates an array or dynamic array {Elements::Formula} object.
@example Create a multi-cell array formula
formula = Xlsxrb.array_formula("SUM(B1:B10*C1:C10)", ref: "A1:C1", cached_value: 0)
@example Create a dynamic array formula
formula = Xlsxrb.array_formula("SORT(UNIQUE(A1:A10))", ref: "D1")
@param expression [String] The formula expression without leading ‘=’. @param ref [String, nil] Target cell or range reference (keyword). @param cached_value [Object, nil] Optional precomputed value. @return [Elements::Formula] @api public
(?strict_excel_mode: bool, ?default_font: untyped?) ?{ (WorkbookBuilder) → void } → Elements::Workbook
Source
# File lib/xlsxrb.rb, line 1306 def self.build(strict_excel_mode: true, default_font: nil) raise Error, "block is required" unless block_given? builder = WorkbookBuilder.new(strict_excel_mode: strict_excel_mode, default_font: default_font) yield builder builder.build end
Builds an in-memory {Elements::Workbook} using a declarative DSL.
@example Build an in-memory workbook
workbook = Xlsxrb.build do |builder| builder.sheet("Overview") do |sheet| sheet.row(["Title", "Date"]) sheet.row(["Report", Date.today]) end end
@note Planned for version 0.3.0: Cell#format_code of the built cells will be the
number format of each cell's resolved style, as in a loaded workbook; cells styled :default or :none will have style index 0; and a style index given in cell_styles will be kept only in Cell#style_index.
@param strict_excel_mode [Boolean] Whether to enforce Microsoft Excel specification limits. @param default_font [Hash, nil] Optional default font options. @yield [builder] @yieldparam builder [Xlsxrb::WorkbookBuilder] @return [Elements::Workbook] The compiled in-memory workbook. @api public
(String | Symbol | Elements::CellError code) → Elements::CellError
Source
# File lib/xlsxrb.rb, line 333 def self.cell_error(code) return code if code.is_a?(Elements::CellError) code_str = code.to_s error_map = { null: "#NULL!", div0: "#DIV/0!", value: "#VALUE!", ref: "#REF!", name: "#NAME?", num: "#NUM!", na: "#N/A", getting_data: "#GETTING_DATA" } resolved_code = error_map[code.to_sym] || code_str Elements::CellError.new(code: resolved_code) end
Creates or returns an {Elements::CellError} object.
@example
err = Xlsxrb.cell_error("#VALUE!") err = Xlsxrb.cell_error(:value)
@param code [String, Symbol, Elements::CellError] Error code or symbol. @return [Elements::CellError] @api public
(Integer row, Integer column) → String
Source
# File lib/xlsxrb.rb, line 467 def self.cell_to_ref(row, column) "#{Elements::Cell._column_letter(column)}#{row + 1}" end
Converts 0-based [row, col] coordinates to an A1-style reference string.
@example
Xlsxrb.cell_to_ref(0, 0) #=> "A1" Xlsxrb.cell_to_ref(99, 54) #=> "BC100"
@param row [Integer] 0-based row index. @param column [Integer] 0-based column index. @return [String] A1-style reference string. @api public
(String | Symbol | Integer col) → Integer
Source
# File lib/xlsxrb.rb, line 481 def self.column_index(col) Elements::Cell._column_index(col) end
Converts a column letter (e.g. “A”, :AA) to a 0-based column index.
@example
Xlsxrb.column_index("A") #=> 0 Xlsxrb.column_index(:AA) #=> 26
@param col [String, Symbol, Integer] Column letter or integer index. @return [Integer] 0-based column index. @api public
(Integer index) → String
Source
# File lib/xlsxrb.rb, line 495 def self.column_letter(index) Elements::Cell._column_letter(index) end
Converts a 0-based column index to an Excel letter (0 -> “A”, 25 -> “Z”, 26 -> “AA”).
@example
Xlsxrb.column_letter(0) #=> "A" Xlsxrb.column_letter(26) #=> "AA"
@param index [Integer] 0-based column index. @return [String] Excel column letter. @api public
(?String? text, ?author: String, ?visible: bool, ?ref: String?, **untyped extra) → Elements::Comment
Source
# File lib/xlsxrb.rb, line 319 def self.comment(text = nil, author: "Author", visible: false, ref: nil, **extra) Elements::Comment.new(text: text, author: author, visible: visible, ref: ref, **extra) end
Creates an {Elements::Comment} object for use in cell comments.
@example Create a cell comment
comment = Xlsxrb.comment("Review this value", author: "Auditor")
@param text [String, nil] Comment body text. @param author [String] Comment author. @param visible [Boolean] Whether comment is visible by default. @param ref [String, nil] Cell coordinate (e.g. “A1”). @return [Elements::Comment] @api public
(Date | Time date_or_time, ?date1904: bool) → (Integer | Float)
Source
# File lib/xlsxrb.rb, line 373 def self.date_to_serial(date_or_time, date1904: false) if date_or_time.is_a?(Time) || date_or_time.is_a?(DateTime) Ooxml::Utils.datetime_to_serial(date_or_time, date1904: date1904) else Ooxml::Utils.date_to_serial(date_or_time, date1904: date1904) end end
Converts a Date or Time to an Excel numeric serial number (1900 or 1904 system).
@example
Xlsxrb.date_to_serial(Date.new(2026, 1, 1)) #=> 46023
@param date_or_time [Date, Time] Date or Time instance. @param date1904 [Boolean] Whether to use the 1904 date system. @return [Integer, Float] Serial number. @api public
(String? formula, ?from_ref: String?, ?to_ref: String?, ?row_delta: Integer?, ?column_delta: Integer?) → String?
Source
# File lib/xlsxrb.rb, line 602 def self.expand_formula(formula, from_ref: nil, to_ref: nil, row_delta: nil, column_delta: nil) return formula if formula.nil? || formula.empty? if from_ref && to_ref f_coords = Elements::Cell._parse_ref(from_ref) t_coords = Elements::Cell._parse_ref(to_ref) return formula unless f_coords && t_coords rd = t_coords[0] - f_coords[0] cd = t_coords[1] - f_coords[1] else rd = row_delta || 0 cd = column_delta || 0 end return formula if rd.zero? && cd.zero? formula.gsub(FORMULA_TOKEN_RE) do |match| m = Regexp.last_match if m[:str] match else c_abs = !m[:col_abs].empty? r_abs = !m[:row_abs].empty? col = m[:col] row = m[:row].to_i col_idx = Elements::Cell._column_index(col) next match if col_idx.nil? || col_idx > 16_383 || row < 1 || row > 1_048_576 new_col = if c_abs || cd.zero? col else ci = col_idx + cd ci = ci.clamp(0, 16_383) Elements::Cell._column_letter(ci) end new_row = if r_abs || rd.zero? row else ri = row + rd ri.clamp(1, 1_048_576) end "#{m[:col_abs]}#{new_col}#{m[:row_abs]}#{new_row}" end end end
Expands a formula by shifting relative cell references from a master cell to a target cell or by offset amounts.
@example Shift formula down one row
Xlsxrb.expand_formula("A2*2", row_delta: 1, column_delta: 0) #=> "A3*2" Xlsxrb.expand_formula("A2*2", from_ref: "B2", to_ref: "B3") #=> "A3*2"
@example Shift formula with absolute references
Xlsxrb.expand_formula("$A$1+A2", row_delta: 2, column_delta: 0) #=> "$A$1+A4"
@param formula [String, nil] Formula expression to expand. @param from_ref [String, nil] Master cell reference (e.g. “B2”). @param to_ref [String, nil] Target cell reference (e.g. “B3”). @param row_delta [Integer, nil] Row shift amount (positive = down, negative = up). @param column_delta [Integer, nil] Column shift amount (positive = right, negative = left). @return [String, nil] Expanded formula expression. @api public
(untyped value, ?String? format_code, ?date1904: bool) → String
Source
# File lib/xlsxrb.rb, line 359 def self.format_value(value, format_code = nil, date1904: false) NumberFormatter.format(value, format_code, date1904: date1904) end
Formats a cell value according to an Excel format code string.
@param value [Object, nil] Value to format. @param format_code [String, nil] Excel format code string. @param date1904 [Boolean] Whether the 1904 date system is active. @return [String] Formatted string representation. @api public
(String expression, ?cached_value: (String | Numeric | bool | Elements::CellError | nil), ?type: (Symbol | String)?, ?ref: String?, ?shared_index: Integer?) → Elements::Formula
Source
# File lib/xlsxrb.rb, line 224 def self.formula(expression, cached_value: nil, type: nil, ref: nil, shared_index: nil) Elements::Formula.new( expression: expression, cached_value: cached_value, type: type || (shared_index ? :shared : nil), ref: ref, shared_index: shared_index, calculate_always: cached_value.nil? || nil ) end
Creates an {Elements::Formula} object for use in cell values.
@example Create a formula without precalculated value
formula = Xlsxrb.formula("SUM(A1:A10)")
@example Create a formula with precomputed cached value
formula = Xlsxrb.formula("A1+B1", cached_value: 42)
@param expression [String] The formula expression without leading ‘=’ (e.g. “SUM(A1:A10)”). @param cached_value [Object, nil] Optional precomputed value for readers that do not evaluate formulas. @param type [Symbol, String, nil] Formula type (:shared, :array, etc.). @param ref [String, nil] Target cell or range reference (e.g. “A1:C1”). @param shared_index [Integer, nil] Shared formula group index (0-based). @return [Elements::Formula] @api public
(?String? url, ?display: String?, ?tooltip: String?, ?location: String?) → Elements::Hyperlink
Source
# File lib/xlsxrb.rb, line 303 def self.hyperlink(url = nil, display: nil, tooltip: nil, location: nil) Elements::Hyperlink.new(url: url, display: display, tooltip: tooltip, location: location) end
Creates an {Elements::Hyperlink} object for use in cell hyperlinks.
@example Create an external hyperlink with a ScreenTip tooltip
link = Xlsxrb.hyperlink("https://example.com", tooltip: "Visit Example")
@example Create an internal worksheet link
link = Xlsxrb.hyperlink(location: "Sheet2!A1", tooltip: "Go to Sheet 2")
@param url [String, nil] External hyperlink URL. @param display [String, nil] Optional display label. @param tooltip [String, nil] Optional hover ScreenTip text. @param location [String, nil] Optional internal sheet coordinate. @return [Elements::Hyperlink] @api public
(untyped source, ?password: String?, ?trim_empty_rows: bool, ?pad_empty_rows: bool, ?pad_empty_cells: bool, ?max_uncompressed_size: Integer?) → Elements::Workbook
Source
# File lib/xlsxrb.rb, line 835 def self.load(source, password: nil, trim_empty_rows: false, pad_empty_rows: false, pad_empty_cells: false, max_uncompressed_size: nil) prepared_source = prepare_source_io(source, password) zip_options = {} zip_options[:max_uncompressed_size] = max_uncompressed_size if max_uncompressed_size zip_reader = Ooxml::ZipReader.open(prepared_source, **zip_options) begin workbook_path = resolve_workbook_entry(zip_reader) wb_dir = File.dirname(workbook_path) wb_rels_name = wb_dir == "." ? "_rels/#{File.basename(workbook_path)}.rels" : "#{wb_dir}/_rels/#{File.basename(workbook_path)}.rels" rels_xml = zip_reader.read_entry(wb_rels_name) wb_rels = rels_xml && !rels_xml.empty? ? Ooxml::RelationshipsParser.parse_all(rels_xml) : EMPTY_RELS rels = wb_rels[:targets] rel_types = wb_rels[:types] sst_entry = resolve_part_entry(zip_reader, rels, "sharedStrings", "sharedStrings.xml", wb_dir) shared_strings_xml = sst_entry ? zip_reader.read_entry(sst_entry) : nil shared_strings = shared_strings_xml ? Ooxml::SharedStringsParser.parse(shared_strings_xml) : [] styles_entry = resolve_part_entry(zip_reader, rels, "styles", "styles.xml", wb_dir) styles_xml = styles_entry ? zip_reader.read_entry(styles_entry) : nil styles = styles_xml ? Ooxml::StylesParser.parse(styles_xml) : {} workbook_xml = zip_reader.read_entry(workbook_path) wb_parsed = Ooxml::WorkbookParser.parse_with_properties(workbook_xml) workbook_sheets = wb_parsed[:sheets] is_date1904 = wb_parsed[:date1904] defined_names = wb_parsed[:defined_names] || [] persons_loaded = false persons_map_cache = nil persons_resolver = lambda do unless persons_loaded persons_loaded = true persons_map_cache = resolve_persons_map(zip_reader: zip_reader, workbook_rels: wb_rels[:entries]) end persons_map_cache end non_worksheet_sheets = [] ws_idx = 0 sheets = workbook_sheets.filter_map do |sheet_info| r_id = sheet_info[:r_id] target = rels[r_id] rel_type = rel_types[r_id] if non_worksheet_relationship?(rel_type, target) non_worksheet_sheets << sheet_info.merge(target: target, type: rel_type) next end sheet_path = resolve_sheet_entry(zip_reader, target, wb_dir, ws_idx) current_sheet_idx = ws_idx ws_idx += 1 next unless sheet_path sheet_xml = zip_reader.read_entry(sheet_path) sheet_name = sheet_info[:name] pa = extract_sheet_print_area(defined_names, sheet_name, current_sheet_idx) pt = extract_sheet_print_titles(defined_names, sheet_name, current_sheet_idx) build_worksheet( sheet_name, sheet_xml, shared_strings, styles, state: sheet_info[:state] || :visible, zip_reader: zip_reader, entry_name: sheet_path, date1904: is_date1904, trim_empty_rows: trim_empty_rows, pad_empty_rows: pad_empty_rows, pad_empty_cells: pad_empty_cells, print_area: pa, print_titles: pt, persons_resolver: persons_resolver ) end wb_unmapped = {} wb_props = {} wb_props[:date1904] = true if is_date1904 wb_props[:active_sheet] = wb_parsed[:active_tab] unless wb_parsed[:active_tab].nil? wb_props[:active_sheet_index] = wb_parsed[:active_tab] unless wb_parsed[:active_tab].nil? wb_props[:first_sheet] = wb_parsed[:first_sheet] unless wb_parsed[:first_sheet].nil? wb_props[:show_sheet_tabs] = wb_parsed[:show_sheet_tabs] unless wb_parsed[:show_sheet_tabs].nil? wb_props[:tab_ratio] = wb_parsed[:tab_ratio] unless wb_parsed[:tab_ratio].nil? wb_props[:full_calc_on_load] = wb_parsed[:full_calc_on_load] unless wb_parsed[:full_calc_on_load].nil? wb_props[:code_name] = wb_parsed[:code_name] if wb_parsed[:code_name] wb_unmapped[:workbook_properties] = wb_props unless wb_props.empty? wb_unmapped[:non_worksheet_sheets] = non_worksheet_sheets unless non_worksheet_sheets.empty? wb_unmapped[:workbook_protection] = wb_parsed[:workbook_protection] if wb_parsed[:workbook_protection] core_xml = zip_reader.read_entry("docProps/core.xml") if core_xml && !core_xml.empty? c_listener = Ooxml::Reader::CorePropertiesListener.new Ooxml::XmlParser.parse(core_xml, c_listener) wb_unmapped[:core_properties] = c_listener.properties unless c_listener.properties.empty? end app_xml = zip_reader.read_entry("docProps/app.xml") if app_xml && !app_xml.empty? a_listener = Ooxml::Reader::AppPropertiesListener.new Ooxml::XmlParser.parse(app_xml, a_listener) wb_unmapped[:app_properties] = a_listener.properties unless a_listener.properties.empty? end custom_xml = zip_reader.read_entry("docProps/custom.xml") if custom_xml && !custom_xml.empty? cu_listener = Ooxml::Reader::CustomPropertiesListener.new Ooxml::XmlParser.parse(custom_xml, cu_listener) wb_unmapped[:custom_properties] = cu_listener.properties unless cu_listener.properties.empty? end Elements::Workbook.new( sheets: sheets, shared_strings: shared_strings, styles: styles, unmapped_data: wb_unmapped, defined_names: defined_names ) ensure zip_reader&.close end end
Loads all sheets into memory, returning an {Elements::Workbook} where every worksheet is a fully-parsed {Elements::Worksheet} supporting coordinate random access. The underlying zip resources are closed immediately.
@example
wb = Xlsxrb.load("report.xlsx") puts wb["Sheet1"]["A1"].value
@param source [String, IO, StringIO] Path to the .xlsx file or an IO-like stream. @param password [String, nil] Password for decrypting password-protected (ECMA-376 Standard/Agile) workbooks. @param trim_empty_rows [Boolean] Whether to omit trailing empty rows from worksheet data. @param pad_empty_rows [Boolean] Whether to pad missing rows with empty row objects. @param pad_empty_cells [Boolean] Whether to pad missing cells within rows with nil cells. @param max_uncompressed_size [Integer, nil] Maximum uncompressed file size threshold in bytes for zip bomb protection. @return [Elements::Workbook] The fully loaded in-memory workbook. @api public
(untyped index, ?alpha: bool) → String?
Source
# File lib/xlsxrb.rb, line 662 def self.palette_color(index, alpha: false) Colors.palette_color(index, alpha: alpha) end
Resolves an ECMA-376 indexed color palette index (0..63) to an RRGGBB hex string (or AARRGGBB if alpha: true).
@example
Xlsxrb.palette_color(12) #=> "0000FF" Xlsxrb.palette_color(12, alpha: true) #=> "FF0000FF"
@param index [Object, nil] Palette index (0..63). @param alpha [Boolean] Whether to prefix “FF” alpha channel. @return [String, nil] @api public
(String? range_ref) → [[Integer, Integer], [Integer, Integer]]?
Source
# File lib/xlsxrb.rb, line 508 def self.parse_range(range_ref) return nil if range_ref.nil? || range_ref.empty? parts = range_ref.split(":", 2) first = Elements::Cell._parse_ref(parts[0]) return nil unless first second = parts[1] ? Elements::Cell._parse_ref(parts[1]) : first return nil unless second top_row = [first[0], second[0]].min bottom_row = [first[0], second[0]].max left_col = [first[1], second[1]].min right_col = [first[1], second[1]].max [[top_row, left_col], [bottom_row, right_col]] end
Converts a cell range reference string (e.g. “A1:C10”, “A1”) to 0-based [[top_row, left_col], [bottom_row, right_col]].
@example
Xlsxrb.parse_range("A1:C10") #=> [[0, 0], [9, 2]]
@param range_ref [String, nil] @return [Array([Integer, Integer], [Integer, Integer]), nil] @api public
(String? ref) → [Integer, Integer]?
Source
# File lib/xlsxrb.rb, line 452 def self.parse_ref(ref) Elements::Cell._parse_ref(ref) end
Converts a cell reference string (e.g. “A1”, “BC100”) to 0-based [row, col] coordinates.
@example
Xlsxrb.parse_ref("A1") #=> [0, 0] Xlsxrb.parse_ref("BC100") #=> [99, 54]
@param ref [String, nil] Excel cell reference string. @return [Array(Integer, Integer), nil] 0-based [row, col] tuple, or nil if invalid. @api public
(Integer | [[Integer, Integer], [Integer, Integer]] top_row_or_bounds, ?Integer? left_column, ?Integer? bottom_row, ?Integer? right_column) → String
Source
# File lib/xlsxrb.rb, line 542 def self.range_to_ref(top_row_or_bounds, left_column = nil, bottom_row = nil, right_column = nil) if top_row_or_bounds.is_a?(Array) first, second = top_row_or_bounds top_row = first[0] left_col = first[1] bot_row = second[0] rgt_col = second[1] else top_row = top_row_or_bounds left_col = left_column || 0 bot_row = bottom_row || top_row rgt_col = right_column || left_col end if top_row == bot_row && left_col == rgt_col cell_to_ref(top_row, left_col) else "#{cell_to_ref(top_row, left_col)}:#{cell_to_ref(bot_row, rgt_col)}" end end
Converts 0-based bounding coordinates to an A1-style range reference string. Accepts either 4 flat integers (top_row, left_column, bottom_row, right_column) or a nested pair ([[top_row, left_column], [bottom_row, right_column]]) as returned by parse_range.
@example 4 flat integers
Xlsxrb.range_to_ref(0, 0, 9, 2) #=> "A1:C10"
@example Nested pair from parse_range
Xlsxrb.range_to_ref([[0, 0], [9, 2]]) #=> "A1:C10"
@param top_row_or_bounds [Integer, Array] 0-based start row index or nested bounding coordinates. @param left_column [Integer, nil] 0-based start column index. @param bottom_row [Integer, nil] 0-based end row index. @param right_column [Integer, nil] 0-based end column index. @return [String] A1-style range reference string. @api public
(untyped source, ?password: String?, ?trim_empty_rows: bool, ?pad_empty_rows: bool, ?pad_empty_cells: bool, ?max_uncompressed_size: Integer?) { (StreamSheet) → void } → void
(untyped source, ?password: String?, ?trim_empty_rows: bool, ?pad_empty_rows: bool, ?pad_empty_cells: bool, ?max_uncompressed_size: Integer?) → Enumerator[StreamSheet, void]
Source
# File lib/xlsxrb.rb, line 752 def self.read(source, password: nil, trim_empty_rows: false, pad_empty_rows: false, pad_empty_cells: false, max_uncompressed_size: nil, &) # The prepared source is what the Enumerator reads, so that it is prepared once. source = prepare_source_io(source, password) 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? zip_options = {} zip_options[:max_uncompressed_size] = max_uncompressed_size if max_uncompressed_size zip_reader = Ooxml::ZipReader.open(source, **zip_options) begin workbook_path = resolve_workbook_entry(zip_reader) wb_dir = File.dirname(workbook_path) wb_rels_name = wb_dir == "." ? "_rels/#{File.basename(workbook_path)}.rels" : "#{wb_dir}/_rels/#{File.basename(workbook_path)}.rels" rels_xml = zip_reader.read_entry(wb_rels_name) rels, rel_types = parse_workbook_relationships(rels_xml) sst_entry = resolve_part_entry(zip_reader, rels, "sharedStrings", "sharedStrings.xml", wb_dir) shared_strings_xml = sst_entry ? zip_reader.read_entry(sst_entry) : nil shared_strings = shared_strings_xml ? Ooxml::SharedStringsParser.parse(shared_strings_xml) : [] styles_entry = resolve_part_entry(zip_reader, rels, "styles", "styles.xml", wb_dir) styles_xml = styles_entry ? zip_reader.read_entry(styles_entry) : nil styles = styles_xml ? Ooxml::StylesParser.parse(styles_xml) : {} workbook_xml = zip_reader.read_entry(workbook_path) wb_parsed = Ooxml::WorkbookParser.parse_with_properties(workbook_xml) workbook_sheets = wb_parsed[:sheets] is_date1904 = wb_parsed[:date1904] ws_idx = 0 workbook_sheets.each do |sheet_info| r_id = sheet_info[:r_id] target = rels[r_id] rel_type = rel_types[r_id] next if non_worksheet_relationship?(rel_type, target) sheet_path = resolve_sheet_entry(zip_reader, target, wb_dir, ws_idx) current_sheet_idx = ws_idx ws_idx += 1 next unless sheet_path chunk_supplier = ->(&blk) { zip_reader.each_entry_chunk(sheet_path, &blk) } stream_sheet = StreamSheet.new( sheet_info[:name], chunk_supplier, shared_strings, styles, zip_reader: zip_reader, entry_name: sheet_path, state: sheet_info[:state] || :visible, date1904: is_date1904, trim_empty_rows: trim_empty_rows, pad_empty_rows: pad_empty_rows, pad_empty_cells: pad_empty_cells, defined_names: wb_parsed[:defined_names] || [], sheet_index: current_sheet_idx ) yield stream_sheet end nil ensure zip_reader&.close end end
Reads an XLSX file (streaming and lazy-loaded by default) from a file path, IO stream, or binary String.
Sheets and rows are streamed lazily with O(1) constant memory. If a block is given, yields each {StreamSheet} sequentially. Call {StreamSheet#load} to convert a sheet to an in-memory representation for coordinate random access (‘sheet`).
@example Streaming read across sheets and rows (O(1) constant memory)
Xlsxrb.read("large.xlsx") do |sheet| puts "Sheet: #{sheet.name}" sheet.each_row do |row| row.each_cell { |cell| puts "#{cell.ref}: #{cell.value}" } end end
@param source [String, IO, StringIO] File path, binary content string, or readable IO stream. @param password [String, nil] Optional password to decrypt password-protected XLSX files. @param trim_empty_rows [Boolean] Whether to omit trailing empty rows during sheet iteration. @param pad_empty_rows [Boolean] Whether to yield empty rows for skipped row numbers. @param pad_empty_cells [Boolean] Whether to pad missing cells within rows. @param max_uncompressed_size [Integer, nil] Maximum allowed uncompressed size in bytes per entry (ZIP bomb defense). @yield [sheet] @yieldparam sheet [StreamSheet] The streaming worksheet object. @return [Enumerator<StreamSheet>, void] @raise [ZipBombError] If an uncompressed entry exceeds max_uncompressed_size. @raise [EncryptedFileError] If the file is encrypted and no password was supplied. @raise [InvalidPasswordError] If the supplied password is incorrect. @raise [ParseError] If the spreadsheet XML structure is invalid. @api public
(*(Hash[Symbol, untyped] | Elements::RichTextRun | String | Array[untyped] | untyped) runs, ?text: String?, ?base_font: untyped, **untyped font_props) → Elements::RichText
Source
# File lib/xlsxrb.rb, line 151 def self.rich_text(*runs, text: nil, base_font: nil, **font_props) base = if base_font.respond_to?(:to_font_hash) base_font.to_font_hash elsif base_font.respond_to?(:to_h) base_font.to_h else base_font end if text f = font_props.empty? ? nil : font_props f = base.merge(f || {}) if base.is_a?(Hash) runs = [Elements::RichTextRun.new(text: text, font: f)] elsif runs.size == 1 && runs.first.is_a?(String) && !font_props.empty? f = base.is_a?(Hash) ? base.merge(font_props) : font_props runs = [Elements::RichTextRun.new(text: runs.first, font: f)] else normalized_runs = [] pending_font = nil runs.each do |item| if item.respond_to?(:to_font_hash) pending_font = item.to_font_hash elsif item.is_a?(Hash) && !item.key?(:text) pending_font = item elsif item.is_a?(Elements::RichTextRun) normalized_runs << item pending_font = nil elsif item.is_a?(Hash) f = item[:font] || pending_font f = f.to_font_hash if f.respond_to?(:to_font_hash) normalized_runs << Elements::RichTextRun.new(text: item[:text].to_s, font: f) pending_font = nil elsif item.is_a?(Array) t = item[0].to_s f = item[1] || pending_font f = f.to_font_hash if f.respond_to?(:to_font_hash) f = f.to_h if f.respond_to?(:to_h) && !f.is_a?(Hash) normalized_runs << Elements::RichTextRun.new(text: t, font: f.is_a?(Hash) ? f : nil) pending_font = nil elsif pending_font normalized_runs << Elements::RichTextRun.new(text: item.to_s, font: pending_font) pending_font = nil else normalized_runs << Elements::RichTextRun.new(text: item.to_s) end end if base.is_a?(Hash) && !base.empty? normalized_runs = normalized_runs.map do |run| merged_font = run.font ? base.merge(run.font) : base.dup Elements::RichTextRun.new(text: run.text, font: merged_font) end end runs = normalized_runs end Elements::RichText.new(runs: runs) end
Helper to construct {Elements::RichText} objects with formatted text runs.
@example Create multi-run rich text with hashes
rt = Xlsxrb.rich_text({ text: "Total: ", font: { bold: true } }, { text: "$100" })
@example Create rich text with text/font pairs
rt = Xlsxrb.rich_text("Normal text, ", ["bold text, ", { bold: true }], ["red text", { color: "FF0000" }])
@example Create rich text with format objects implementing to_font_hash
rt = Xlsxrb.rich_text("Normal text, ", bold_format, "bold text")
@example Create simple styled text
rt = Xlsxrb.rich_text(text: "Important Notice", bold: true, color: "FF0000")
@param runs [Array<Hash, String, Array, Elements::RichTextRun, Object>] Optional array of rich text run items. @param text [String, nil] Plain text string (convenience parameter). @param base_font [Hash, Object, nil] Base font properties to merge into all runs. @param font_props [Hash] Inline font styling options (e.g. bold: true, color: “FF0000”). @return [Elements::RichText] The compiled rich text element. @api public
(untyped name, ?replace_char: String) → String
Source
# File lib/xlsxrb.rb, line 696 def self.sanitize_sheet_name(name, replace_char: "_") DslHelpers.sanitize_sheet_name(name, replace_char: replace_char) end
Sanitizes a worksheet name to ensure it conforms to Excel constraints within 31 characters. Replaces forbidden characters (\ / ? * [ ] : and control characters), replaces leading/trailing apostrophes, and replaces reserved ‘History’ with ‘History_’.
@example
Xlsxrb.sanitize_sheet_name("Sales: 2026") #=> "Sales_ 2026" Xlsxrb.sanitize_sheet_name("'Report'") #=> "_Report_"
@param name [Object] Desired worksheet name. @param replace_char [String] Replacement character for invalid characters. @return [String] Excel-compliant worksheet name. @api public
(Numeric serial, ?date1904: bool) → Date
Source
# File lib/xlsxrb.rb, line 406 def self.serial_to_date(serial, date1904: false) Ooxml::Utils.serial_to_date(serial, date1904: date1904) end
Converts an Excel serial number to a Date.
@example
Xlsxrb.serial_to_date(46023) #=> #<Date: 2026-01-01>
@param serial [Numeric] Excel serial number. @param date1904 [Boolean] Whether to use the 1904 date system. @return [Date] @api public
(Numeric serial, ?date1904: bool) → Time
Source
# File lib/xlsxrb.rb, line 438 def self.serial_to_time(serial, date1904: false) Ooxml::Utils.serial_to_datetime(serial, date1904: date1904) end
Converts an Excel serial number to a Time (UTC).
@example
Xlsxrb.serial_to_time(46023.5) #=> 2026-01-01 12:00:00 UTC
@param serial [Numeric] Excel serial number. @param date1904 [Boolean] Whether to use the 1904 date system. @return [Time] @api public
(String? cell_ref) → [String, Integer]?
Source
# File lib/xlsxrb.rb, line 572 def self.split_coordinate(cell_ref) return nil unless cell_ref coords = Elements::Cell._parse_ref(cell_ref) return nil unless coords row_idx, col_idx = coords [Elements::Cell._column_letter(col_idx), row_idx + 1] end
Splits an A1-style cell reference into its column name and 1-based row number.
@example
Xlsxrb.split_coordinate("A1") #=> ["A", 1] Xlsxrb.split_coordinate("BC100") #=> ["BC", 100]
@param cell_ref [String, nil] Excel cell reference string. @return [Array(String, Integer), nil] [col_name, row_number] tuple (1-based row), or nil if invalid. @api public
(Time | Date time, ?date1904: bool) → Float
Source
# File lib/xlsxrb.rb, line 420 def self.time_to_serial(time, date1904: false) if time.is_a?(Time) || time.is_a?(DateTime) Ooxml::Utils.datetime_to_serial(time, date1904: date1904) else Ooxml::Utils.date_to_serial(time, date1904: date1904).to_f end end
Converts a Time or Date to a fractional Excel serial number.
@example
Xlsxrb.time_to_serial(Time.utc(2026, 1, 1, 12, 0, 0)) #=> 46023.5
@param time [Time, Date] Time or Date instance. @param date1904 [Boolean] Whether to use the 1904 date system. @return [Float] Fractional serial number. @api public
(Integer | String | Symbol | nil color, ?alpha: bool) → String?
Source
# File lib/xlsxrb.rb, line 679 def self.to_hex_color(color, alpha: false) Colors.to_hex(color, alpha: alpha) end
Converts any supported color representation (palette index 0..63, CSS name, #RGB, #RRGGBB, #AARRGGBB, integer RGB) to a normalized hex string.
@example
Xlsxrb.to_hex_color(12) #=> "0000FF" Xlsxrb.to_hex_color(:navy) #=> "000080" Xlsxrb.to_hex_color("#FF0000") #=> "FF0000"
@param color [Integer, String, Symbol, nil] @param alpha [Boolean] Whether to include the alpha channel (default false -> “RRGGBB”). @return [String, nil] @api public
(String text) → String
Source
# File lib/xlsxrb.rb, line 718 def self.truncate_cell_text(text) DslHelpers.truncate_cell_text(text) end
Cuts text to what a cell holds: 32,767 characters counted in UTF-16 code units, as Excel counts them, so a character outside the Basic Multilingual Plane, such as an emoji, counts as two. A character is never split. Writing longer text raises ArgumentError with strict_excel_mode (the default); call this first to keep the start of the text instead.
Text of 32,767 bytes or fewer always fits, so it is returned as is after its byte size is checked, without counting its characters. Longer text is returned as a new UTF-8 String, even if it fits.
@example
Xlsxrb.truncate_cell_text("x" * 40_000).length #=> 32767 Xlsxrb.truncate_cell_text("😀" * 20_000).length #=> 16383
@param text [String] @return [String] @api public
(untyped serial, ?date1904: bool) → bool
Source
# File lib/xlsxrb.rb, line 392 def self.valid_excel_date?(serial, date1904: false) Ooxml::Utils.valid_excel_date?(serial, date1904: date1904) end
Checks whether a serial number is a valid Excel date within the supported range.
@example
Xlsxrb.valid_excel_date?(46023) #=> true Xlsxrb.valid_excel_date?(-1) #=> false
@param serial [Object] Serial number candidate. @param date1904 [Boolean] Whether to use the 1904 date system. @return [Boolean] @api public
(?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
Source
# File lib/xlsxrb.rb, line 1021 def self.write(target_or_workbook = OMITTED_TARGET, workbook_or_nil = nil, password: nil, encryption_mode: nil, strict_excel_mode: true, default_font: nil, shared_strings: true, compression_level: DEFAULT_COMPRESSION_LEVEL, &) if block_given? if target_or_workbook.equal?(OMITTED_TARGET) io = StringIO.new io.binmode 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, &) return io.string.b end target = target_or_workbook raise Error, "target is required" if target.nil? if password && !password.empty? buf = StringIO.new buf.binmode stream_writer = StreamWriter.new(buf, strict_excel_mode: strict_excel_mode, default_font: default_font, shared_strings: shared_strings, compression_level: compression_level) begin yield stream_writer stream_writer.close plain_bytes = buf.string.b encrypted_bytes = Ooxml::Crypto.encrypt(plain_bytes, password, mode: write_encryption_mode(encryption_mode)) if target.is_a?(String) File.binwrite(target, encrypted_bytes) elsif target.respond_to?(:write) target.write(encrypted_bytes) end ensure stream_writer.cleanup! end else stream_writer = StreamWriter.new(target, strict_excel_mode: strict_excel_mode, default_font: default_font, shared_strings: shared_strings, compression_level: compression_level) begin yield stream_writer stream_writer.close ensure stream_writer.cleanup! end end return end if workbook_or_nil.nil? raise Error, "workbook must be an Elements::Workbook" if target_or_workbook.equal?(OMITTED_TARGET) wb = target_or_workbook raise Error, "workbook must be an Elements::Workbook" unless wb.is_a?(Elements::Workbook) io = StringIO.new io.binmode write(io, wb, password: password, encryption_mode: encryption_mode, shared_strings: shared_strings, compression_level: compression_level) return io.string.b end target = target_or_workbook workbook = workbook_or_nil raise Error, "target is required" if target.nil? raise Error, "workbook must be an Elements::Workbook" unless workbook.is_a?(Elements::Workbook) if shared_strings sst = [] sst_index = {} if workbook.shared_strings && !workbook.shared_strings.empty? workbook.shared_strings.each do |val| if (val.is_a?(String) || val.is_a?(Elements::RichText)) && !sst_index.key?(val) sst << val sst_index[val] = sst.size - 1 end end end else sst = nil sst_index = nil end # Collect shared strings and build index without allocating new Hashes sheet_data = workbook.sheets.map do |raw_ws| ws = raw_ws.respond_to?(:load) ? raw_ws.load : raw_ws if sst_index ws.rows.each do |row| row.cells.each do |cell| val = cell.value if (val.is_a?(String) || val.is_a?(Elements::RichText)) && !sst_index.key?(val) sst << val sst_index[val] = sst.size - 1 end end end end columns = ws.columns.map do |col| # simplecov:disable # Edge case / untested delegation block style_idx = col.unmapped_data&.[](:style_index) || col.unmapped_data&.[](:style) || (col.respond_to?(:style_index) && col.style_index) min = col.unmapped_data&.[](:min) max = col.unmapped_data&.[](:max) { index: col.index, width: col.width, hidden: col.hidden?, custom_width: col.custom_width?, best_fit: col.best_fit?, collapsed: col.collapsed?, outline_level: col.outline_level, style_index: style_idx, min: min, max: max } # simplecov:enable end sd = { name: ws.name, rows: ws.rows, columns: columns } sd[:charts] = ws.charts unless ws.charts.empty? sd[:conditional_formats] = ws.conditional_formats unless ws.conditional_formats.empty? sd[:data_validations] = ws.data_validations unless ws.data_validations.empty? sd[:state] = ws.state if ws.respond_to?(:state) && ws.state && ws.state != :visible sd[:comments] = ws.comments if ws.respond_to?(:comments) && !ws.comments.empty? if ws.respond_to?(:hyperlinks) && !ws.hyperlinks.empty? sd[:hyperlinks] = if ws.hyperlinks.is_a?(Hash) ws.hyperlinks.map do |cell_ref, link| entry = if link.is_a?(Hash) link.dup else (link.respond_to?(:to_h) ? link.to_h : { url: link }) end entry[:ref] ||= cell_ref entry end else ws.hyperlinks end end sd[:sparkline_groups] = ws.sparkline_groups if ws.respond_to?(:sparkline_groups) && !ws.sparkline_groups.empty? sd[:sheet_properties] = ws.sheet_properties if ws.respond_to?(:sheet_properties) && ws.sheet_properties && !ws.sheet_properties.empty? sd[:sheet_format] = ws.sheet_format if ws.respond_to?(:sheet_format) && ws.sheet_format && !ws.sheet_format.empty? 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? 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? sd[:ignored_errors] = ws.ignored_errors if ws.respond_to?(:ignored_errors) && !ws.ignored_errors.empty? 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 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 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 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 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? if ws.respond_to?(:selection) && ws.selection sd[:selection] = if ws.selection.is_a?(Array) ws.selection.map { |sel| sel.respond_to?(:to_h) ? sel.to_h : sel } else ws.selection.respond_to?(:to_h) ? ws.selection.to_h : ws.selection end end sd[:selection] ||= ws.sheet_view[:selection] if ws.respond_to?(:sheet_view) && ws.sheet_view.is_a?(Hash) && ws.sheet_view[:selection] 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? 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? 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? 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? 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? 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? sd[:merge_cells] = ws.merged_cells if ws.respond_to?(:merged_cells) && ws.merged_cells && !ws.merged_cells.empty? sd[:auto_filter] = ws.auto_filter if ws.respond_to?(:auto_filter) && ws.auto_filter 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?) 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 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? 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? sd[:threaded_comments] = ws.threaded_comments if ws.respond_to?(:threaded_comments) && ws.threaded_comments && !ws.threaded_comments.empty? sd[:header_footer_images] = ws.header_footer_images if ws.respond_to?(:header_footer_images) && ws.header_footer_images && !ws.header_footer_images.empty? if ws.respond_to?(:row_breaks) && ws.row_breaks && !ws.row_breaks.empty? sd[:row_breaks] = ws.row_breaks.map { |r| r.respond_to?(:to_h) ? r.to_h : r } end if ws.respond_to?(:column_breaks) && ws.column_breaks && !ws.column_breaks.empty? sd[:column_breaks] = ws.column_breaks.map { |c| c.respond_to?(:to_h) ? c.to_h : c } end sd[:background_image] = ws.background_image if ws.respond_to?(:background_image) && ws.background_image if ws.respond_to?(:images) && ws.images && !ws.images.empty? sd[:images] = ws.images.map do |img| if img.is_a?(Elements::Image) ext = img.filename ? File.extname(img.filename).delete_prefix(".").downcase : "png" opts = img.unmapped_data ? img.unmapped_data.dup : {} opts[:name] ||= img.name opts[:file_data] = img.data opts[:ext] = ext opts[:from_column] = img.from_column opts[:from_row] = img.from_row opts[:to_column] = img.to_column opts[:to_row] = img.to_row opts else img end end end sd[:shapes] = ws.shapes if ws.respond_to?(:shapes) && ws.shapes && !ws.shapes.empty? # Extract facade metadata from unmapped_data as fallback facade = ws.unmapped_data[:facade] if ws.respond_to?(:unmapped_data) && ws.unmapped_data.is_a?(Hash) facade&.each { |key, val| sd[key] = val unless sd.key?(key) } sd end # Extract workbook-level facade metadata wb_facade = workbook.unmapped_data[:facade] || {} wb_properties = (workbook.unmapped_data[:workbook_properties] || wb_facade[:workbook_properties] || {}).merge( workbook.respond_to?(:workbook_properties) && workbook.workbook_properties ? workbook.workbook_properties.to_h : {} ) wb_core = (workbook.respond_to?(:core_properties) && workbook.core_properties) || wb_facade[:core_properties] wb_app = (workbook.respond_to?(:app_properties) && workbook.app_properties) || wb_facade[:app_properties] wb_custom = (workbook.respond_to?(:custom_properties) && workbook.custom_properties) || wb_facade[:custom_properties] wb_prot = (workbook.respond_to?(:workbook_protection) && workbook.workbook_protection) || wb_facade[:workbook_protection] raw_dns = wb_facade[:defined_names] || (workbook.respond_to?(:defined_names) && !workbook.defined_names.empty? ? workbook.defined_names : nil) defined_names = if raw_dns raw_dns.map { |dn| dn.is_a?(Elements::MetadataRecord) ? dn.to_h : dn.dup } else [] end # Auto-generate _xlnm.Print_Area and _xlnm.Print_Titles from worksheet definitions if not already present workbook.sheets.each_with_index do |ws, idx| sheet_name = ws.name || "Sheet#{idx + 1}" quoted_sheet = DslHelpers.quote_sheet_name(sheet_name) if ws.respond_to?(:print_area) && ws.print_area && defined_names.none? { |dn| dn[:name] == "_xlnm.Print_Area" && (dn[:local_sheet_id] == idx || dn[:local_sheet_name] == sheet_name) } val = ws.print_area.split(",").map { |part| "#{quoted_sheet}!#{DslHelpers.absolute_range(part.strip)}" }.join(",") defined_names << { name: "_xlnm.Print_Area", value: val, local_sheet_id: idx } end 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) } pt = ws.print_titles pt = pt.to_h if pt.is_a?(Elements::MetadataRecord) parts = [] col_val = pt[:columns] parts << "#{quoted_sheet}!$#{col_val.sub(":", ":$")}" if col_val parts << "#{quoted_sheet}!$#{pt[:rows].sub(":", ":$")}" if pt[:rows] defined_names << { name: "_xlnm.Print_Titles", value: parts.join(","), local_sheet_id: idx } unless parts.empty? end defined_names = nil if defined_names.empty? if password && !password.empty? buf = StringIO.new buf.binmode Ooxml::WorkbookWriter.write( buf, sheets: sheet_data, shared_strings: sst, shared_strings_index: sst_index, styles: workbook.styles, defined_names: defined_names, core_properties: wb_core, app_properties: wb_app, custom_properties: wb_custom, workbook_protection: wb_prot, workbook_properties: wb_properties, compression_level: compression_level ) encrypted_bytes = Ooxml::Crypto.encrypt(buf.string.b, password, mode: write_encryption_mode(encryption_mode)) if target.is_a?(String) File.binwrite(target, encrypted_bytes) elsif target.respond_to?(:write) target.write(encrypted_bytes) end else Ooxml::WorkbookWriter.write( target, sheets: sheet_data, shared_strings: sst, shared_strings_index: sst_index, styles: workbook.styles, defined_names: defined_names, core_properties: wb_core, app_properties: wb_app, custom_properties: wb_custom, workbook_protection: wb_prot, workbook_properties: wb_properties, compression_level: compression_level ) end end
Writes an XLSX file or IO stream (streaming or in-memory), or returns a binary string.
@overload write(?target, password: nil, encryption_mode: nil, strict_excel_mode: true, &block)
Streaming write: yields a {StreamWriter} context for high-speed, zero-allocation XLSX generation.
If target is omitted, returns the generated XLSX as an in-memory binary String.
@param target [String, IO, StringIO, nil] Optional destination file path or writable IO object.
@param password [String, nil] Optional password to encrypt the generated XLSX file.
@param encryption_mode [Symbol, nil] Encryption scheme used with a password: `:agile` (AES-256, with a check
that the file is unchanged) or `:standard` (AES-128; deprecated, and an error from 0.3.0). When omitted,
Standard is written in 0.2 and Agile from 0.3.0. See docs/adr/0013-write-agile-encryption-read-both.md.
@param strict_excel_mode [Boolean] Whether to enforce Microsoft Excel specification limits.
@yield [stream_writer]
@yieldparam stream_writer [Xlsxrb::StreamWriter]
@return [String, void] Binary data if target is omitted, or void if written to target.
@overload write(workbook, password: nil, encryption_mode: nil)
In-memory write: exports the workbook to an in-memory binary String. @param workbook [Elements::Workbook] The workbook to write. @param password [String, nil] Optional password to encrypt the binary string. @param encryption_mode [Symbol, nil] Encryption scheme used with a password: `:agile` (AES-256, with a check that the file is unchanged) or `:standard` (AES-128; deprecated, and an error from 0.3.0). When omitted, Standard is written in 0.2 and Agile from 0.3.0. See docs/adr/0013-write-agile-encryption-read-both.md. @return [String] Binary data representing the XLSX file.
@overload write(target, workbook, password: nil, encryption_mode: nil)
In-memory write: writes the workbook to a file path or IO stream. @param target [String, IO, StringIO] Destination file path or writable IO object. @param workbook [Elements::Workbook] The workbook to write. @param password [String, nil] Optional password to encrypt the output file. @param encryption_mode [Symbol, nil] Encryption scheme used with a password: `:agile` (AES-256, with a check that the file is unchanged) or `:standard` (AES-128; deprecated, and an error from 0.3.0). When omitted, Standard is written in 0.2 and Agile from 0.3.0. See docs/adr/0013-write-agile-encryption-read-both.md. @return [void]
@example Streaming write to file
Xlsxrb.write("output.xlsx") do |writer| writer.sheet("Sheet1") { |s| s.row(["Hello", "World"]) } end
@example Streaming write to in-memory binary string (target omitted)
binary_data = Xlsxrb.write do |writer| writer.sheet("Sheet1") { |s| s.row(["Hello", "World"]) } end
@example Password-protected streaming write
Xlsxrb.write("protected.xlsx", password: "SecretPassword123") do |writer| writer.sheet("Confidential") { |s| s.row(["Private Data", 100]) } end
@example In-memory export to binary string (for Rails send_data & mailers)
binary_data = Xlsxrb.write(workbook)
@api public @param shared_strings [Boolean] Whether to intern strings in a shared strings table (xl/sharedStrings.xml).
When set to `false`, strings are emitted directly as inline strings (`<c t="inlineStr">`), providing flat $O(1)$ constant memory during streaming write. Disabling shared strings is recommended when streaming large datasets where cells contain unique text (e.g. log exports, transaction details).
@param compression_level [Integer, nil] ZIP deflate compression level (0..9, or Zlib::DEFAULT_COMPRESSION
for zlib's level 6). Defaults to {DEFAULT_COMPRESSION_LEVEL}. Higher levels write smaller files more slowly;
level 0 stores entries without compression. See docs/adr/0009-default-zip-compression-level.md.