xlsxrb 0.2.0 → 0.2.1

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4e4682f8228d5ffbe3681efdc627a082ac3b7c5b037d619b921c541e0c14b0fe
4
- data.tar.gz: c8950a741c0ddfc4a0e7db66d514a9fb4a343ea5c9054b579891d2429289d6ff
3
+ metadata.gz: 6eed4936f201a7a8a3090b4d1ca8cb4609992b663565f94cb66e62137adc1def
4
+ data.tar.gz: 733afe59d5c49dddcc508fb4fe8db66e2c41bec971c7a057debebd2b5f6c9dbd
5
5
  SHA512:
6
- metadata.gz: '0964cde67e062b9704140855bf2bd5bf06a2ae8484c2dab7d9158afb2e6a8ab86afb6de9654aa7c75bb659478ecee492a340ec3a1ae0da7c5798de055091d695'
7
- data.tar.gz: 77a3927cd829adf6a7481bb25965a95e3282f59a91bf688f6e10fb19cdaa0076586bb3a2e641b975f1b9a707e6dde39d510bd408fe2991175e4f2d26d0c05dc5
6
+ metadata.gz: 31a5bc6068cf43cc0d878cc3232cecfcab8e4669e2a36435752ec212ba70a204813f0e1b216817e81397f5ed5f56973f9a1ea8e2a91c5b6bcbcb61141bf11482
7
+ data.tar.gz: 9e1614094509557f10679da61b2fc58b2abf21f2853472479ce424adc35da304e509a1094144cb1b8c28d8ca40b3e1da031a290fa594bd04042120c9cf59e9e9
data/CHANGELOG.md CHANGED
@@ -1,3 +1,40 @@
1
+ ## [0.2.1] - 2026-11-16
2
+
3
+ ### Changed
4
+ - Write styled cells faster in `Xlsxrb.write` with a block (`StreamWriter`). Writing 50,000 rows of 10 cells with every cell styled takes longer than writing them unstyled by 48% with a `row_style` (0.2.0: 131%), 45% with one `cell_styles` name (148%), 89% with a per-column `cell_styles` array (217%), and 45% with column styles (198%), on Ruby 4.0 without YJIT. With YJIT the differences are 49%, 49%, 76%, and 35% (120%, 142%, 195%, and 223%). Each figure is the fastest of three processes that each run one case seven times and take the median. The written files are unchanged.
5
+ - Build and write styled cells faster with `Xlsxrb.build` and `Xlsxrb.write(target, workbook)`. Building and writing the same rows with every cell styled takes longer than unstyled rows by 4% with a `row_style` (0.2.0: 40%), 13% with one `cell_styles` name (41%), 20% with a per-column `cell_styles` array (44%), and 7% with column styles (40%), on Ruby 4.0 without YJIT. With YJIT the differences are 18%, 20%, 41%, and 25% (46%, 46%, 41%, and 49%). Unstyled rows also build and write in 25% less time than in 0.2.0, and 37% less with YJIT. `Xlsxrb.build` creates each cell once, with its style index, instead of creating it with the style name first. The built workbooks and written files are unchanged.
6
+ - `WorkbookBuilder#sheet` and `WorkbookBuilder#[]` return a `DeferredWorksheet` instead of an `Elements::Worksheet`. It answers the same methods with the same results, and builds the worksheet the first time one of them is called or when it is frozen. `is_a?(Elements::Worksheet)` is false for it, and its RBS type changed. This breaks the rule that patch releases keep public APIs compatible; it is made in 0.2.1 as an exception, because returning a built worksheet would create every cell of the sheet twice.
7
+ - `WorksheetBuilder#row`, `#<<`, `#skip_rows`, and `#group_rows` with row indexes raise `Xlsxrb::Error` after the sheet's block ends, instead of ignoring the rows.
8
+
9
+ ### Deprecated
10
+ - Using the sheet that `WorkbookBuilder#sheet` and `WorkbookBuilder#[]` return (`DeferredWorksheet`) is deprecated and warns on first use; read sheets from the workbook that `Xlsxrb.build` returns. In version 0.3.0, `WorkbookBuilder#sheet` will return the sheet's `WorksheetBuilder`, and `WorkbookBuilder#[]` will return the `WorksheetBuilder` of an existing sheet ([ADR 0010](docs/adr/0010-one-dsl-for-built-and-streamed-workbooks.md)).
11
+ - Adding a sheet with `WorkbookBuilder#[]` is deprecated and warns when the call is given a name or an index, or no argument after a sheet was added; use `WorkbookBuilder#sheet`. In version 0.3.0, `#[]` will look sheets up as `StreamWriter#[]` does: it will return the `WorksheetBuilder` of an existing sheet, or of the current sheet without an argument, and raise for a sheet that does not exist. `w[0]` now adds a sheet named `"0"`.
12
+ - Using the value that `style` returns, on `Xlsxrb.build` and `Xlsxrb.write` writers and their sheets, is deprecated and warns on first use; configure the style with options or in the block given to `style`. In version 0.3.0, `style` will return `nil`. The returned value (`ReturnedStyleBuilder`) still changes the style. Changing a style after cells use it styles those cells differently in `Xlsxrb.build` and `StreamWriter`.
13
+ - Changing a sheet setting that `StreamWriter` writes at the start of the sheet after rows of the sheet are written is deprecated and warns: `column`, `freeze_pane`, `split_pane`, `selection`, `sheet_view`, `sheet_format`, `sheet_properties`, `outline_properties`, `tab_color=`, `code_name=`, `fit_to_page=`, and `page_setup` with `fit_to_width` or `fit_to_height`. Make these settings before the first row. Such a setting applies only while the first rows are held back, and is dropped without an error once about 64 KB of rows are written. In version 0.3.0, it will raise `Xlsxrb::Error`.
14
+ - Looking up a sheet that does not exist with `StreamWriter#[]` is deprecated and warns; create sheets with `StreamWriter#sheet`. In version 0.3.0, it will raise `ArgumentError`. Writing to such a sheet already raises `Xlsxrb::Error`.
15
+ - In version 0.3.0, `StreamWriter#sheet` will return the sheet's writer (`WorksheetProxy`) instead of its name, as `WorkbookBuilder#sheet` will return the sheet's `WorksheetBuilder`. A return value cannot be checked when it is used, so this does not warn. Code that looks the sheet up by the returned name, as in `w[w.sheet("A")]`, can use the returned writer instead.
16
+ - `WorksheetBuilder#build` is deprecated and warns; it will be private in version 0.3.0.
17
+ - In version 0.3.0, cells built by `Xlsxrb.build` will change as follows. `Cell#format_code` will be the number format of the cell's resolved style, as in a loaded workbook; it is now set only for styles defined on the sheet with a String name, and only as the format was when the row was added. Cells styled `:default` or `:none` will have style index 0 instead of the name. A style index given in `cell_styles` will be kept only in `Cell#style_index`, not also in `Cell#style`.
18
+
19
+ ### Fixed
20
+ - Count cell text and sheet names in UTF-16 code units for Excel's limits (32,767 and 31), as Excel does ([ADR 0011](docs/adr/0011-count-excel-text-limits-as-excel-does.md)). Characters outside the Basic Multilingual Plane, such as emoji, count as two. Counting Unicode characters let `strict_excel_mode` write files that Excel repairs, such as a cell with 16,384 emoji or a sheet name with 16. `Elements::Worksheet.valid_name?` and `validate` count the same way, and `DslHelpers.sanitize_sheet_name` cuts a name to 31 code units without splitting a character.
21
+ - Raise `ArgumentError` for cell text longer than 32,767 characters in `StreamWriter` with `strict_excel_mode` (the default), as `Xlsxrb.build` does. The check never ran, so such text was written and Excel cut it when repairing the file. With `strict_excel_mode: false` it is written as before.
22
+ - Write cell text that looks like an `_xHHHH_` escape, and characters that XML 1.0 cannot hold, so that Excel and `Xlsxrb.load` read the text back as written, in all writers. `"_x0041_"` was read back as `"A"`, because the leading underscore was not written as `_x005F_`, and characters such as U+0001 and U+FFFE were dropped; they are now written as `_x0001_` and `_xFFFE_`. Shared strings, inline strings, rich text runs, and cached formula strings are encoded this way (ECMA-376 `ST_Xstring`).
23
+ - Return `nil` from `row`, `skip_rows`, and `group_rows` in `Xlsxrb.build` and `StreamWriter` sheets, as documented. `Xlsxrb.build` returned its internal list of rows from `row`, and both modes returned the next row index from `skip_rows` and the block's value or the row indexes from `group_rows`.
24
+ - Report a sheet that was never created when writing to it through `StreamWriter#[]`. The error said that the sheet was no longer active, as for an earlier sheet.
25
+ - Write negative integers with their value in `StreamWriter` rows that have a row style, height, or other row attribute, or in sheets with column styles. Unstyled cells in such rows took the value from a lookup table indexed from its end, so `-1` was written as `65535`.
26
+ - Give `Date` and `Time` cells without a cell style the default date and date-time number formats in `StreamWriter` rows that have a row style, height, or other row attribute, and in sheets with column styles ([#9](https://github.com/niku/xlsxrb/issues/9)). A cell that inherits a row or column style without a number format gets a variant of that style with the date format, as a cell style already did, so it keeps the style's font, fill, and border. These cells were written without a number format, so Excel showed the serial number.
27
+ - Write values that claim to be a `Time` through `is_a?` without being one, such as `ActiveSupport::TimeWithZone`, as date-times with their own wall clock, in `Xlsxrb.build` and `StreamWriter`. `case`/`when` did not match them as `Time`, so they were written as text inside a number cell, which Excel repairs. `Xlsxrb.build` keeps them as `Time` values with the same wall clock.
28
+ - Give `Date` and `Time` cells without a cell style, in `Xlsxrb.build` rows that have a row style or in sheets with column styles, a variant of the inherited style with the default date or date-time format, as `StreamWriter` does. These cells were given the default format alone, so they lost the row or column style's font, fill, and border.
29
+ - Leave the `cell_styles` Array given to `WorksheetBuilder#row` in `Xlsxrb.build` unchanged. A `Date` or `Time` cell without a style wrote the default date style into the caller's Array, so the next row given the same Array got that date style in the same column.
30
+ - Keep the threaded comments of styled cells in the workbook that `Xlsxrb.build` returns. Those cells lost `Cell#threaded_comments` when their style names were resolved. Written files were not affected, because threaded comments are written from the sheet's list.
31
+ - Raise `ArgumentError` when a Hash given to `cell_styles:` has a style option as a key or a value that is not a style, as in `cell_styles: { bold: true }`. Such a Hash maps columns to styles, so `{ bold: true }` was read as column BOLD and failed with a column-limit error, and `{ b: true }` was ignored. The message shows how to give inline styles.
32
+ - Give `Date` and `Time` cells in `StreamWriter` rows the date variant of their style's current definition. After a style was defined again with `style`, its date cells kept the variant made from the earlier definition.
33
+ - Style the cells of `Xlsxrb.build` with the definition a style had when each row, or column style, was added, as `StreamWriter` does. A style defined again later, in the workbook or in any sheet, changed the cells of every sheet, including rows added before it. A style used before any definition still takes its first definition.
34
+ - Write the Playground `quick_start`, `sales_report`, and `sheet_properties` preset formulas with `s.formula(...)`. Since 0.2.0 plain strings starting with `=` are written as text, so these presets showed `=D12` and similar strings instead of computed values.
35
+ - Write the formulas in the Visual Gallery `sheet_properties` example with `s.formula(...)`, so its second sheet shows computed totals instead of `=SUM(...)` text.
36
+ - Render Japanese text in the Playground's LibreOffice preview. The ZetaOffice build ships no CJK font, so Japanese characters showed as boxes, including in the `japanese_text` preset. `rake fetch_assets` now downloads Noto Sans JP Regular and Bold (SIL Open Font License 1.1, license published next to the fonts), and the Playground installs them before LibreOffice starts.
37
+
1
38
  ## [0.2.0] - 2026-11-10
2
39
 
3
40
  Upgrading from 0.1.x: see [docs/UPGRADING-0.2.md](docs/UPGRADING-0.2.md).
data/README.md CHANGED
@@ -101,9 +101,9 @@ require "xlsxrb"
101
101
 
102
102
  Xlsxrb.write("large_output.xlsx") do |writer|
103
103
  writer.sheet("Sales Data") do |sheet|
104
+ sheet.column(0, width: 15.5)
104
105
  sheet.row(["Date", "Amount", "Status"])
105
106
  sheet.row([Date.today, 100, true])
106
- sheet.column(0, width: 15.5)
107
107
  end
108
108
  end
109
109
  ```
@@ -189,12 +189,14 @@ module Xlsxrb
189
189
  #
190
190
  # @param styles [untyped]
191
191
  # @return [untyped]
192
+ # @raise [ArgumentError] If the Hash looks like an inline style rather than columns mapped to styles.
192
193
  #: (untyped styles) -> untyped
193
194
  def self.normalize_row_styles(styles)
194
195
  return styles unless styles.is_a?(Hash)
195
196
 
196
197
  styles_array = []
197
198
  styles.each do |k, v|
199
+ check_column_style!(k, v)
198
200
  if k.is_a?(Range) || k.is_a?(Array)
199
201
  k.each { |idx| styles_array[Elements::Cell._column_index(idx)] = v }
200
202
  else
@@ -204,6 +206,31 @@ module Xlsxrb
204
206
  styles_array
205
207
  end
206
208
 
209
+ # Hint for a cell_styles Hash that reads like an inline style.
210
+ INLINE_CELL_STYLES_HINT = "a Hash given to cell_styles maps columns to styles; " \
211
+ "pass inline styles in an Array, as in cell_styles: [{ bold: true }], " \
212
+ "or style the whole row with row_style: { bold: true }"
213
+
214
+ # Raises when an entry of a cell_styles Hash cannot be a column mapped to a style:
215
+ # a style option name as the key (a column name has at most three letters), or a
216
+ # value that is not a style name, a style index, an inline style, or nil.
217
+ #
218
+ # @param column [Object] The entry's key.
219
+ # @param style [Object] The entry's value.
220
+ # @return [void]
221
+ # @raise [ArgumentError]
222
+ #: (untyped column, untyped style) -> void
223
+ def self.check_column_style!(column, style)
224
+ raise ArgumentError, "#{column.inspect} is a style option, but #{INLINE_CELL_STYLES_HINT}" if StyleBuilder::OPTION_KEYS.include?(column)
225
+
226
+ case style
227
+ when nil, String, Symbol, Integer, Hash
228
+ nil
229
+ else
230
+ raise ArgumentError, "#{style.inspect} for column #{column.inspect} is not a style; #{INLINE_CELL_STYLES_HINT}"
231
+ end
232
+ end
233
+
207
234
  # Style names that select the workbook's default cell format.
208
235
  DEFAULT_STYLE_NAMES = [:default, :none, "default", "none"].freeze
209
236
 
@@ -773,6 +800,24 @@ module Xlsxrb
773
800
  FORBIDDEN_SHEET_CHARS = %r{[\\/?*\[\]:]|[\x00-\x08\x0B\x0C\x0E-\x1F]}
774
801
  MAX_SHEET_NAME_LENGTH = 31
775
802
 
803
+ MAX_CELL_TEXT_LENGTH = 32_767
804
+
805
+ # Raises ArgumentError if +text+ is longer than a cell holds: 32,767 UTF-16 code units,
806
+ # as Excel counts it (ADR 0011). Text of N UTF-16 code units has at least N bytes, so
807
+ # callers on hot paths call this only for text longer than MAX_CELL_TEXT_LENGTH bytes,
808
+ # which bytesize tells in O(1).
809
+ #
810
+ # @param text [String]
811
+ # @return [void]
812
+ # @raise [ArgumentError]
813
+ #: (String text) -> void
814
+ def self.check_cell_text_length!(text)
815
+ length = Ooxml::Utils.utf16_length(text)
816
+ return if length <= MAX_CELL_TEXT_LENGTH
817
+
818
+ raise ArgumentError, "Cell text length #{length} exceeds Excel limit of 32,767 characters, counted in UTF-16 code units as Excel does"
819
+ end
820
+
776
821
  # Sanitizes a worksheet name to ensure it conforms to Excel constraints within 31 characters.
777
822
  # Replaces forbidden characters (\ / ? * [ ] : and control characters),
778
823
  # replaces leading/trailing apostrophes, and replaces reserved 'History' with 'History_'.
@@ -787,7 +832,10 @@ module Xlsxrb
787
832
  str = str.sub(/\A'+/) { replace_char * Regexp.last_match(0).length }
788
833
  str = "Sheet" if str.empty?
789
834
 
790
- base = str[0, MAX_SHEET_NAME_LENGTH].sub(/'+\z/) { replace_char * Regexp.last_match(0).length }
835
+ # Excel counts the limit in UTF-16 code units (ADR 0011); keep whole characters.
836
+ units = 0
837
+ base = str.each_char.take_while { |char| (units += Ooxml::Utils.utf16_length(char)) <= MAX_SHEET_NAME_LENGTH }.join
838
+ base = base.sub(/'+\z/) { replace_char * Regexp.last_match(0).length }
791
839
  return "#{base}#{replace_char}" if base.casecmp?("History")
792
840
 
793
841
  base
@@ -1052,7 +1052,7 @@ module Xlsxrb
1052
1052
  def self.valid_name?(name)
1053
1053
  case name
1054
1054
  when String
1055
- !name.empty? && name.size <= 31 && !name.match?(FORBIDDEN_NAME_CHARS) && !name.start_with?("'") && !name.end_with?("'") && !name.casecmp?("History")
1055
+ !name.empty? && Ooxml::Utils.utf16_length(name) <= 31 && !name.match?(FORBIDDEN_NAME_CHARS) && !name.start_with?("'") && !name.end_with?("'") && !name.casecmp?("History")
1056
1056
  else
1057
1057
  false
1058
1058
  end
@@ -1070,7 +1070,7 @@ module Xlsxrb
1070
1070
  if name.nil? || !name.is_a?(String) || name.empty?
1071
1071
  errs << "worksheet name must be a non-empty String (got #{name.inspect})"
1072
1072
  else
1073
- errs << "worksheet name cannot exceed 31 characters (got #{name.size})" if name.size > 31
1073
+ errs << "worksheet name cannot exceed 31 characters, counted in UTF-16 code units (got #{Ooxml::Utils.utf16_length(name)})" if Ooxml::Utils.utf16_length(name) > 31
1074
1074
  errs << "worksheet name cannot contain \\, /, ?, *, [, ], or :" if name.match?(FORBIDDEN_NAME_CHARS)
1075
1075
  errs << "worksheet name cannot start or end with an apostrophe" if name.start_with?("'") || name.end_with?("'")
1076
1076
  errs << "worksheet name 'History' is reserved by Excel" if name.casecmp?("History")
@@ -66,7 +66,20 @@ module Xlsxrb
66
66
  # Default date-time format code used by Writer for Time cells.
67
67
  DEFAULT_DATETIME_FORMAT = "yyyy\\-mm\\-dd\\ hh:mm:ss"
68
68
 
69
+ # First bytes of the four-byte UTF-8 sequences, which encode the characters outside
70
+ # the Basic Multilingual Plane: two UTF-16 code units each.
71
+ SUPPLEMENTARY_LEAD_BYTES = [0xF0, 0x2D, 0xF4].pack("C*").freeze # "\xF0-\xF4", a range for String#count
72
+ private_constant :SUPPLEMENTARY_LEAD_BYTES
73
+
69
74
  class << self
75
+ # The length of UTF-8 text in UTF-16 code units, the unit Excel counts its text
76
+ # limits in (ADR 0011): one per character, and one more for each character outside
77
+ # the Basic Multilingual Plane, such as an emoji.
78
+ #: (String text) -> Integer
79
+ def utf16_length(text)
80
+ text.length + text.b.count(SUPPLEMENTARY_LEAD_BYTES)
81
+ end
82
+
70
83
  # Checks whether a serial number is a valid Excel date within the supported range.
71
84
  #: (untyped serial, ?date1904: bool) -> bool
72
85
  def valid_excel_date?(serial, date1904: false)
@@ -1257,6 +1257,17 @@ module Xlsxrb
1257
1257
  str.match?(ESCAPE_RE) ? str.gsub(ESCAPE_RE, ESCAPE_MAP) : str
1258
1258
  end
1259
1259
 
1260
+ # Escapes cell text: encodes it as ST_Xstring (XmlBuilder.encode_xstring), so that
1261
+ # text that looks like _xHHHH_ and characters XML 1.0 cannot hold are read back as
1262
+ # written, then escapes the XML special characters.
1263
+ def escape_text(value)
1264
+ str = value.to_s
1265
+ str = str.dup.force_encoding(Encoding::UTF_8) if str.encoding == Encoding::BINARY
1266
+ # Most text has neither; the checks cost less than encode_xstring's own.
1267
+ str = XmlBuilder.encode_xstring(str) if str.include?("_x") || str.match?(INVALID_XML_CHARS_RE)
1268
+ str.match?(ESCAPE_RE) ? str.gsub(ESCAPE_RE, ESCAPE_MAP) : str
1269
+ end
1270
+
1260
1271
  def write_shared_strings_xml(zip)
1261
1272
  return if @shared_strings.empty?
1262
1273
 
@@ -1306,11 +1317,11 @@ module Xlsxrb
1306
1317
  else
1307
1318
  buf << "<r><t>"
1308
1319
  end
1309
- buf << escape_xml(text.to_s) << "</t></r>"
1320
+ buf << escape_text(text.to_s) << "</t></r>"
1310
1321
  end
1311
1322
  buf << "</si>"
1312
1323
  else
1313
- buf << "<si><t>" << escape_xml(str.to_s) << "</t></si>"
1324
+ buf << "<si><t>" << escape_text(str.to_s) << "</t></si>"
1314
1325
  end
1315
1326
 
1316
1327
  if buf.bytesize >= 32_768