xlsxrb 0.2.0 → 0.2.2
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 +88 -0
- data/README.md +25 -3
- data/lib/xlsxrb/dsl_helpers.rb +65 -1
- data/lib/xlsxrb/elements/styles.rb +15 -6
- data/lib/xlsxrb/elements/worksheet.rb +2 -2
- data/lib/xlsxrb/number_formatter.rb +26 -8
- data/lib/xlsxrb/ooxml/cfb.rb +11 -3
- data/lib/xlsxrb/ooxml/crypto/agile.rb +48 -10
- data/lib/xlsxrb/ooxml/crypto/standard.rb +5 -1
- data/lib/xlsxrb/ooxml/crypto.rb +3 -0
- data/lib/xlsxrb/ooxml/shared_strings_parser.rb +26 -8
- data/lib/xlsxrb/ooxml/utils.rb +13 -0
- data/lib/xlsxrb/ooxml/workbook_writer.rb +43 -21
- data/lib/xlsxrb/ooxml/worksheet_parser.rb +116 -12
- data/lib/xlsxrb/ooxml/worksheet_writer.rb +338 -259
- data/lib/xlsxrb/ooxml/writer/drawing_xml.rb +206 -201
- data/lib/xlsxrb/ooxml/writer/features_xml.rb +109 -102
- data/lib/xlsxrb/ooxml/writer/styles_xml.rb +46 -46
- data/lib/xlsxrb/ooxml/writer.rb +167 -160
- data/lib/xlsxrb/ooxml/xml_builder.rb +35 -7
- data/lib/xlsxrb/ooxml/xml_parser.rb +34 -1
- data/lib/xlsxrb/ooxml/zip_reader.rb +95 -68
- data/lib/xlsxrb/ooxml/zip_writer.rb +16 -0
- data/lib/xlsxrb/stream_row.rb +2 -2
- data/lib/xlsxrb/stream_sheet.rb +26 -11
- data/lib/xlsxrb/stream_writer.rb +212 -86
- data/lib/xlsxrb/style_builder.rb +339 -0
- data/lib/xlsxrb/version.rb +1 -1
- data/lib/xlsxrb/workbook_builder.rb +239 -88
- data/lib/xlsxrb/worksheet_builder.rb +847 -139
- data/lib/xlsxrb.rb +87 -21
- data/sig/generated/xlsxrb/dsl_helpers.rbs +37 -0
- data/sig/generated/xlsxrb/elements/styles.rbs +5 -0
- data/sig/generated/xlsxrb/number_formatter.rbs +7 -0
- data/sig/generated/xlsxrb/ooxml/cfb.rbs +2 -0
- data/sig/generated/xlsxrb/ooxml/crypto/agile.rbs +10 -0
- data/sig/generated/xlsxrb/ooxml/shared_strings_parser.rbs +7 -0
- data/sig/generated/xlsxrb/ooxml/utils.rbs +10 -0
- data/sig/generated/xlsxrb/ooxml/workbook_writer.rbs +13 -0
- data/sig/generated/xlsxrb/ooxml/worksheet_parser.rbs +40 -0
- data/sig/generated/xlsxrb/ooxml/worksheet_writer.rbs +53 -0
- data/sig/generated/xlsxrb/ooxml/writer/features_xml.rbs +3 -0
- data/sig/generated/xlsxrb/ooxml/writer.rbs +4 -0
- data/sig/generated/xlsxrb/ooxml/xml_builder.rbs +19 -2
- data/sig/generated/xlsxrb/ooxml/xml_parser.rbs +10 -0
- data/sig/generated/xlsxrb/ooxml/zip_reader.rbs +12 -1
- data/sig/generated/xlsxrb/ooxml/zip_writer.rbs +8 -0
- data/sig/generated/xlsxrb/stream_row.rbs +2 -2
- data/sig/generated/xlsxrb/stream_sheet.rbs +9 -0
- data/sig/generated/xlsxrb/stream_writer.rbs +46 -6
- data/sig/generated/xlsxrb/style_builder.rbs +261 -0
- data/sig/generated/xlsxrb/workbook_builder.rbs +42 -9
- data/sig/generated/xlsxrb/worksheet_builder.rbs +618 -4
- data/sig/generated/xlsxrb.rbs +53 -8
- metadata +9 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 126fcecf7b280d0b6b978cfb12151e67da9d54289718f71a0bdd91186cc810d7
|
|
4
|
+
data.tar.gz: da5c941c4a66c43c3ab7471d68784549ffcdaaf65ac865449b6d73b30aae0104
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: d00259b8db777c33f123b8c9bcc5a3a34121c99c780171aca78c557e08d796fc016d6340cb4ffa551af21447be0bb69dc86a067bc3469422429d65e213441d47
|
|
7
|
+
data.tar.gz: a962faf4eb6892ed08135dc0de71451a77661c70c6da688b606eff8ab090ab948362b671277033d0e3f45266f85d4accbe6d3d2bd3f9b191035529c1054118c5
|
data/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,91 @@
|
|
|
1
|
+
## [0.2.2] - 2026-11-23
|
|
2
|
+
|
|
3
|
+
### Added
|
|
4
|
+
- Add `Xlsxrb.truncate_cell_text`, which cuts text to what a cell holds: 32,767 characters counted in UTF-16 code units, as Excel counts them ([ADR 0011](docs/adr/0011-count-excel-text-limits-as-excel-does.md)). A character is never split, so 20,000 emoji become 16,383. `strict_excel_mode` raises `ArgumentError` for longer text; callers that want to keep the start of the text instead can call this for every cell. Text of 32,767 bytes or fewer is returned as is without being counted.
|
|
5
|
+
|
|
6
|
+
### Deprecated
|
|
7
|
+
- `encryption_mode: :standard` in `Xlsxrb.write` is deprecated and warns; pass `encryption_mode: :agile` ([ADR 0013](docs/adr/0013-write-agile-encryption-read-both.md)). Standard encryption is AES-128 in ECB mode with no check that the file is unchanged, and Agile encryption, which Excel 2010 and later open, is AES-256 with one. In version 0.3.0 `:standard` raises `ArgumentError`, and a password without `encryption_mode:` writes Agile encryption instead of Standard; that change of default gives no warning. Files with either scheme are still read.
|
|
8
|
+
- Passing xlsx data as a String to `Xlsxrb.load` and `Xlsxrb.read` is deprecated and warns; pass a stream, as in `Xlsxrb.load(StringIO.new(data))` ([ADR 0012](docs/adr/0012-the-argument-fixes-what-a-string-means.md)). A String is read as data when it looks like xlsx data and as a file path otherwise, so a program that passes on an uploaded workbook as a String can be made to open a file on the server. In version 0.3.0 a String is always a file path.
|
|
9
|
+
|
|
10
|
+
### Security
|
|
11
|
+
- Check the HMAC of a file encrypted with Agile encryption when reading it, and raise `Xlsxrb::DecryptionError` if the encrypted package does not match it or the file has none. The HMAC was not read at all, so a file changed after it was encrypted could be read without an error. Files written by xlsxrb 0.2.1 and earlier, whose HMAC was computed differently (see Fixed), are still read and checked against that HMAC.
|
|
12
|
+
- Raise `Xlsxrb::ZipError` for a ZIP entry whose declared size runs past the end of the archive, in `Xlsxrb.load`, `Xlsxrb.read`, and `Ooxml::ZipReader`. The size was passed to `IO#read` as the length to read: a 150-byte file declaring 4 GB made Ruby allocate over 1 GB before failing with `Errno::EINVAL`, and a ZIP64 size of 2**62 raised `NoMemoryError`, which `rescue StandardError` does not catch.
|
|
13
|
+
- Stop holding the inflated data of every entry in memory when reading an archive that has no central directory and uses data descriptors. Each entry is inflated to find where it ends, and the output was kept until the reader was closed, so `max_uncompressed_size` (500 MB by default) bounded one entry but not their total: a 2 MB file could hold 2 GB. Such an entry is now inflated once to measure it, without keeping the output, and again when it is read. Its `Entry#compressed_size` and `Entry#crc32` now hold the compressed size and the CRC-32 from the data descriptor instead of the uncompressed size and 0.
|
|
14
|
+
- Raise `Xlsxrb::Error` for an encrypted file (CFB) whose DIFAT lists the same FAT sector more than once. Every listing loaded the sector again, so a 529 KB file given to `Xlsxrb.load` with a password used 1.2 GB, and the use grew in proportion to the file.
|
|
15
|
+
- Raise `Xlsxrb::DecryptionError` for Agile encryption whose `hashSize` differs from the digest length. The password check compared only `hashSize` bytes, so `hashSize="0"` accepted any password; the package was then decrypted with the wrong key into unusable bytes rather than reported as a wrong password.
|
|
16
|
+
- Stop reading a String given to `background_image=` as a file path ([ADR 0012](docs/adr/0012-the-argument-fixes-what-a-string-means.md)). A String that named an existing file was replaced by that file's bytes, which were written into the workbook as the background image without being checked to be an image. A program that passed on an uploaded image as a String could be given text such as `/srv/app/config/secret.txt` and would put that file into the workbook it returned. A String is now always the image itself. To use a file, pass its bytes: `sheet.background_image = { data: File.binread(path), ext: "jpg" }`. This changes a documented behavior in a patch release, as the deprecation policy allows for severe harm; callers that passed a path get a background that is not an image until they change the call.
|
|
17
|
+
- Raise `ArgumentError` when writing an image or background image whose `ext` is not 1 to 10 letters and digits. The extension was written as given into the ZIP entry name, the relationship target, and `[Content_Types].xml`, so an extension taken from an uploaded file name, such as `png/../../../evil`, produced the entry `xl/media/image1.png/../../../evil`, and one containing `"/>` added relationships to the drawing's relationship part.
|
|
18
|
+
- Raise `Xlsxrb::ZipError` from `Ooxml::ZipWriter` for entry names that are empty, start with `/`, contain a `..` segment, a backslash, or a control character. A program that extracts the archive could write such an entry outside its target directory.
|
|
19
|
+
- Escape the `ref` and shared index of array and shared formulas, a row's `outline_level`, the `tint` of rich text colors, and the `id`, `parent_id`, and `timestamp` of threaded comments when writing them as XML attributes. A value containing `"` ended the attribute, so the rest of the value was written as further attributes or elements. A threaded comment `id` read from a file was written back the same way.
|
|
20
|
+
- Escape every option value written as an XML attribute by the workbook, styles, drawing, chart, table, and pivot table writers, and the font options of rich text. More than 500 values were written as given, among them a chart data point `idx`, a pivot table source range, `ref`, and `subtotal`, and a rich text font `size`, `underline`, `vert_align`, and color `theme`. A value containing `"` ended the attribute, so the rest of it was written as further attributes or elements, and one containing `<` or `&` made the part not well-formed. Custom document properties of type `:number`, `:float`, and `:date` are escaped as text in the same way. Values without these characters are written as before.
|
|
21
|
+
- Escape the `ref` and `type` of a cell given to `Ooxml::WorksheetWriter#write_row` as a Hash. They were written into the `r` and `t` attributes of the cell as given, so a value containing `"` could add attributes or elements to the worksheet. The builder and the stream writer do not pass these keys, so only a caller of the private writer was affected.
|
|
22
|
+
- Write a style id into the `s` attribute of a row or cell only when it is an Integer. `Ooxml::WorksheetWriter` wrote the value it found in the style map as given, so a map holding a String containing `"` could add attributes or elements to the worksheet. The builder and the stream writer fill the map with Integers, so only a caller of the private writer was affected.
|
|
23
|
+
- Remove characters that XML 1.0 cannot hold, such as U+0001 and U+FFFE, from attribute values and text written through `Ooxml::XmlBuilder`: hyperlink targets and tooltips, table and column names, defined names, headers and footers, data validation messages, number formats, and document properties. One such character made the part not well-formed, so the file could not be opened. Cell text is unchanged; it keeps these characters as `_xHHHH_`.
|
|
24
|
+
- Fix `Xlsxrb.load`, `StreamSheet#hyperlinks`, and `StreamSheet#load` never returning for a sheet in which the word `hyperlink` appears outside a tag after `<hyperlinks>`, as in `<hyperlinks>hyperlink</hyperlinks>`. The scan returned to the same position forever, and with a `ref` attribute on the enclosing tag it also added an entry on every pass until memory ran out.
|
|
25
|
+
- Read date format codes that contain `%` as literal text in `Cell#formatted_value`, `Row#formatted_values`, and `Xlsxrb.format_value`. The `%` reached `Time#strftime` as a directive, so a format code such as `yyyy%999999d` produced 1 MB of text per cell, and a 3.5 KB file could ask for 1 GB from one call.
|
|
26
|
+
- Raise `Xlsxrb::ParseError` for XML parts whose elements nest more than 256 levels deep. REXML's SAX2 parser takes time proportional to the depth for every tag: 20,000 nested elements (a 2.5 KB file) took 15 seconds in `Xlsxrb.read` and `Xlsxrb.load`, and 40,000 took 58 seconds.
|
|
27
|
+
- Raise `Xlsxrb::ParseError` for a row whose last `<c>` or `<is>` start tag has no end tag. The cell pattern searched to the end of the row once for each such tag, so a row of 40,000 unclosed `<c>` tags (a 3 KB file) took over 100 seconds to read. A `<c>` start tag without an end tag was read as an empty cell before.
|
|
28
|
+
- Read shared strings in time proportional to the part. An `<si>` without `<t>`, and a `<t>` in a string table that has `<rPh>` elements, each searched the rest of the part, so 100,000 empty `<si>` elements (a 4 KB file) took over 60 seconds before the first sheet was read.
|
|
29
|
+
- Find streamed rows in time proportional to the sheet when a row, or markup between rows, spans many chunks. Each 64 KB chunk searched the whole buffer again: 16 MB of elements whose names start with `row` (a 27 KB file) took over 60 seconds, and that buffer had no size limit. Rows and tags over 50 MB now raise `Xlsxrb::ParseError` on every path (it was `ArgumentError`, for unclosed rows only).
|
|
30
|
+
- Raise `Xlsxrb::ParseError` for a row number above 1,048,576, Excel's last row. The number was built digit by digit into an Integer of any size (400,000 digits took over 20 seconds), and `pad_empty_rows: true` yielded one empty row for every number below it.
|
|
31
|
+
- Read cell values of more than 400 characters as text, or raise `Xlsxrb::ParseError` when the cell is typed as a number, instead of converting them to a number. Converting 16 million digits (an 18 KB file) to an Integer took over 20 seconds. Shorter values are read as before. A shared string index that is negative or longer than 10 digits reads as an empty string instead of the last string or `RangeError`.
|
|
32
|
+
- Stop `StreamSheet#dimension`, `#row_range`, and `#column_range` after the first 1 MB of a sheet that has neither `<dimension>` nor `<sheetData>`. They searched everything read so far again for each chunk, so a 16 MB sheet (a 19 KB file) took 19 seconds.
|
|
33
|
+
- Format numbers as General for format codes longer than 1,024 characters (Excel accepts 255). The time to format grows with the code for every cell that uses it.
|
|
34
|
+
- Require rexml 3.4.2 or later (was `~> 3.0`), the first version without the denial of service in parsing XML that has multiple XML declarations (CVE-2025-58767). Earlier 3.x versions have further known denial-of-service advisories.
|
|
35
|
+
- Raise `ArgumentError` for a chart series `type` that is not a known chart type and for a shape color transform whose `type` is not a DrawingML color transform. Both are written as element names: a series type was written as given, so one containing `>` added elements to the chart part, and a transform type was only escaped as text. The `val` of a transform and the alpha of a color are escaped as attribute values.
|
|
36
|
+
|
|
37
|
+
### Fixed
|
|
38
|
+
- Write the HMAC that the specification describes ([MS-OFFCRYPTO] 2.3.4.14) for `encryption_mode: :agile`: over the encrypted package, with its key and value encrypted under the package key. It was computed over the package before encryption and encrypted under keys derived from the password, so a reader that checks the HMAC found every such file changed. Excel 16.115 for Mac and Apache POI 5.2.5 open files written either way.
|
|
39
|
+
- Read an encrypted file whose last sector is shorter than a sector. Excel 2007 ends some files where the last stream ends, without padding; the short sector was dropped, so the encrypted package came out truncated and decryption failed with `Xlsxrb::DecryptionError`.
|
|
40
|
+
- Read a file with Standard encryption that has bytes after the encrypted package. Only the blocks that hold the package are decrypted now; trailing bytes that were not a whole AES block made decryption fail. A package shorter than its declared size raises `Xlsxrb::DecryptionError` instead of being returned truncated.
|
|
41
|
+
- Raise `Xlsxrb::ZipError` for corrupt deflate data and for compression methods other than stored and deflate. These raised `Zlib::DataError` or `Zlib::BufError`, which code that rescues `Xlsxrb::Error` does not catch, and reading an entry with an unsupported compression method through `ZipReader#open_entry_io` returned no data without an error. An archive that ends inside a local file header no longer raises `NoMethodError`.
|
|
42
|
+
- Replace invalid UTF-16 in a part with U+FFFD instead of raising `Encoding::InvalidByteSequenceError`.
|
|
43
|
+
- Raise `Xlsxrb::DecryptionError` for encrypted packages with salts, keys, or ciphertext of the wrong length or invalid Base64. These raised `OpenSSL::Cipher::CipherError` or `ArgumentError`, which code that rescues `Xlsxrb::Error` does not catch.
|
|
44
|
+
- Raise `Xlsxrb::ParseError` for malformed XML and exceeded entity expansion limits in a part, instead of `REXML::ParseException` and `RuntimeError`. Code that rescues `RuntimeError` for these no longer catches them.
|
|
45
|
+
- Return the General form when formatting Infinity or NaN, or a date serial number outside Excel's range, with a format code, instead of raising `FloatDomainError` or `ArgumentError`.
|
|
46
|
+
- Decode each XML entity once in cell text, formulas, and attribute values. The predefined entities were decoded before the numeric ones, so `&#60;`, which is the text `<`, was read as `<`, and `&lt;` written as `&lt;` was read as `<` as well.
|
|
47
|
+
- Read encrypted files stored as version 4 compound files, which have 4,096-byte sectors. The first sector was taken to start 512 bytes into the file, as in version 3, instead of 4,096, so no stream was found and decryption failed.
|
|
48
|
+
- Read bytes that are not UTF-8 in an XML part as U+FFFD. `Xlsxrb.load`, `StreamSheet#dimension`, and reading relationships raised `ArgumentError`, and `Xlsxrb.read` returned cell text that was not valid UTF-8, which raised when it was written or matched. A part that is not well-formed because of such bytes raises `Xlsxrb::ParseError`.
|
|
49
|
+
- Read a cell style index or a parent style (`xfId`) outside the style table as no style. One too large for a machine word raised `RangeError` in `Cell#formatted_value` and `Row#formatted_values`, and a negative `xfId` took the parent counted from the end of the table.
|
|
50
|
+
- Raise the decryption error for an encrypted workbook given as a stream. An error while decrypting, such as `Xlsxrb::InvalidPasswordError` for a wrong password, was discarded, and reading went on to raise `Xlsxrb::ZipError` for the encrypted bytes. A String source was not affected.
|
|
51
|
+
|
|
52
|
+
## [0.2.1] - 2026-11-16
|
|
53
|
+
|
|
54
|
+
### Changed
|
|
55
|
+
- 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.
|
|
56
|
+
- 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.
|
|
57
|
+
- `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.
|
|
58
|
+
- `WorksheetBuilder#row`, `#<<`, `#skip_rows`, and `#group_rows` with row indexes raise `Xlsxrb::Error` after the sheet's block ends, instead of ignoring the rows.
|
|
59
|
+
|
|
60
|
+
### Deprecated
|
|
61
|
+
- 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)).
|
|
62
|
+
- 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"`.
|
|
63
|
+
- 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`.
|
|
64
|
+
- 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`.
|
|
65
|
+
- 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`.
|
|
66
|
+
- 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.
|
|
67
|
+
- `WorksheetBuilder#build` is deprecated and warns; it will be private in version 0.3.0.
|
|
68
|
+
- 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`.
|
|
69
|
+
|
|
70
|
+
### Fixed
|
|
71
|
+
- 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.
|
|
72
|
+
- 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.
|
|
73
|
+
- 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`).
|
|
74
|
+
- 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`.
|
|
75
|
+
- 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.
|
|
76
|
+
- 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`.
|
|
77
|
+
- 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.
|
|
78
|
+
- 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.
|
|
79
|
+
- 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.
|
|
80
|
+
- 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.
|
|
81
|
+
- 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.
|
|
82
|
+
- 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.
|
|
83
|
+
- 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.
|
|
84
|
+
- 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.
|
|
85
|
+
- 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.
|
|
86
|
+
- Write the formulas in the Visual Gallery `sheet_properties` example with `s.formula(...)`, so its second sheet shows computed totals instead of `=SUM(...)` text.
|
|
87
|
+
- 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.
|
|
88
|
+
|
|
1
89
|
## [0.2.0] - 2026-11-10
|
|
2
90
|
|
|
3
91
|
Upgrading from 0.1.x: see [docs/UPGRADING-0.2.md](docs/UPGRADING-0.2.md).
|
data/README.md
CHANGED
|
@@ -92,6 +92,26 @@ Xlsxrb.read("large_file.xlsx") do |sheet|
|
|
|
92
92
|
end
|
|
93
93
|
```
|
|
94
94
|
|
|
95
|
+
### Reading from a File or from Memory
|
|
96
|
+
|
|
97
|
+
`Xlsxrb.read` and `Xlsxrb.load` take the workbook from a file path or from a stream:
|
|
98
|
+
|
|
99
|
+
| Source | Pass | Example |
|
|
100
|
+
| :--- | :--- | :--- |
|
|
101
|
+
| A file | Its path, as a String | `Xlsxrb.load("workbook.xlsx")` |
|
|
102
|
+
| xlsx data in memory, such as an upload | A stream (an IO) | `Xlsxrb.load(StringIO.new(data))` |
|
|
103
|
+
| An open file | The IO | `File.open("workbook.xlsx", "rb") { \|file\| Xlsxrb.load(file) }` |
|
|
104
|
+
|
|
105
|
+
```ruby
|
|
106
|
+
require "xlsxrb"
|
|
107
|
+
require "stringio"
|
|
108
|
+
|
|
109
|
+
# In a web application: read the uploaded workbook, not a file named by the upload.
|
|
110
|
+
workbook = Xlsxrb.load(StringIO.new(params[:file].read))
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
A String is a file path. Passing xlsx data as a String still works in 0.2 and warns: xlsxrb tells the two apart by the content of the String, so data that someone else supplied can be made to name a file on the machine instead ([ADR 0012](docs/adr/0012-the-argument-fixes-what-a-string-means.md)). From 0.3.0 a String is always a path. A path that comes from someone you do not trust opens whatever it names; check it before passing it, as with `File.open`.
|
|
114
|
+
|
|
95
115
|
### Streaming Write (Low Memory)
|
|
96
116
|
|
|
97
117
|
Pipes row and cell XML directly to the archive without buffering rows in memory:
|
|
@@ -101,9 +121,9 @@ require "xlsxrb"
|
|
|
101
121
|
|
|
102
122
|
Xlsxrb.write("large_output.xlsx") do |writer|
|
|
103
123
|
writer.sheet("Sales Data") do |sheet|
|
|
124
|
+
sheet.column(0, width: 15.5)
|
|
104
125
|
sheet.row(["Date", "Amount", "Status"])
|
|
105
126
|
sheet.row([Date.today, 100, true])
|
|
106
|
-
sheet.column(0, width: 15.5)
|
|
107
127
|
end
|
|
108
128
|
end
|
|
109
129
|
```
|
|
@@ -192,13 +212,13 @@ puts "Formulas: #{sheet.rows.flat_map(&:cells).select(&:formula?).map { |c| [c.r
|
|
|
192
212
|
|
|
193
213
|
### Password Protection & Encryption ([MS-OFFCRYPTO])
|
|
194
214
|
|
|
195
|
-
|
|
215
|
+
Reads files encrypted with Standard or Agile encryption and writes encrypted files, without external C extensions:
|
|
196
216
|
|
|
197
217
|
```ruby
|
|
198
218
|
require "xlsxrb"
|
|
199
219
|
|
|
200
220
|
# Write password-protected file
|
|
201
|
-
Xlsxrb.write("confidential.xlsx", password: "SecretPassword123") do |writer|
|
|
221
|
+
Xlsxrb.write("confidential.xlsx", password: "SecretPassword123", encryption_mode: :agile) do |writer|
|
|
202
222
|
writer.sheet("Financials") { |sheet| sheet.row(["Assets", 5_000_000]) }
|
|
203
223
|
end
|
|
204
224
|
|
|
@@ -208,6 +228,8 @@ Xlsxrb.read("confidential.xlsx", password: "SecretPassword123") do |sheet|
|
|
|
208
228
|
end
|
|
209
229
|
```
|
|
210
230
|
|
|
231
|
+
`encryption_mode: :agile` writes AES-256 with a check that the file is unchanged, which Excel 2010 and later open. Without it, 0.2 writes Standard encryption (AES-128, no such check); from 0.3.0 a password always writes Agile encryption, and `encryption_mode: :standard` warns in 0.2 and is an error from 0.3.0 ([ADR 0013](docs/adr/0013-write-agile-encryption-read-both.md)). Files with either scheme are read.
|
|
232
|
+
|
|
211
233
|
### Date and Time Handling
|
|
212
234
|
|
|
213
235
|
Excel stores dates and times as serial numbers (days since 1900, with the time of day as the fraction) and marks them as dates only through the cell's number format. `cell.value` returns that serial number as an Integer or Float. To get dates back:
|
data/lib/xlsxrb/dsl_helpers.rb
CHANGED
|
@@ -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,40 @@ 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
|
+
|
|
821
|
+
# Cuts +text+ to the whole characters that fit in a cell: 32,767 UTF-16 code units, as
|
|
822
|
+
# Excel counts them (ADR 0011). Text of 32,767 bytes or fewer always fits and is returned
|
|
823
|
+
# as is, so most text is not counted. Longer text is returned as a new UTF-8 String.
|
|
824
|
+
#
|
|
825
|
+
# @param text [String]
|
|
826
|
+
# @return [String]
|
|
827
|
+
#: (String text) -> String
|
|
828
|
+
def self.truncate_cell_text(text)
|
|
829
|
+
return text if text.bytesize <= MAX_CELL_TEXT_LENGTH
|
|
830
|
+
|
|
831
|
+
units = text.encode(Encoding::UTF_16LE).byteslice(0, MAX_CELL_TEXT_LENGTH * 2) #: String
|
|
832
|
+
# A cut between the two code units of a character leaves a lone high surrogate.
|
|
833
|
+
units = units.byteslice(0, units.bytesize - 2) unless units.valid_encoding? #: String
|
|
834
|
+
units.encode(Encoding::UTF_8)
|
|
835
|
+
end
|
|
836
|
+
|
|
776
837
|
# Sanitizes a worksheet name to ensure it conforms to Excel constraints within 31 characters.
|
|
777
838
|
# Replaces forbidden characters (\ / ? * [ ] : and control characters),
|
|
778
839
|
# replaces leading/trailing apostrophes, and replaces reserved 'History' with 'History_'.
|
|
@@ -787,7 +848,10 @@ module Xlsxrb
|
|
|
787
848
|
str = str.sub(/\A'+/) { replace_char * Regexp.last_match(0).length }
|
|
788
849
|
str = "Sheet" if str.empty?
|
|
789
850
|
|
|
790
|
-
|
|
851
|
+
# Excel counts the limit in UTF-16 code units (ADR 0011); keep whole characters.
|
|
852
|
+
units = 0
|
|
853
|
+
base = str.each_char.take_while { |char| (units += Ooxml::Utils.utf16_length(char)) <= MAX_SHEET_NAME_LENGTH }.join
|
|
854
|
+
base = base.sub(/'+\z/) { replace_char * Regexp.last_match(0).length }
|
|
791
855
|
return "#{base}#{replace_char}" if base.casecmp?("History")
|
|
792
856
|
|
|
793
857
|
base
|
|
@@ -469,7 +469,7 @@ module Xlsxrb
|
|
|
469
469
|
# @api public
|
|
470
470
|
#: (Integer? style_index) -> String?
|
|
471
471
|
def number_format(style_index)
|
|
472
|
-
return nil unless style_index
|
|
472
|
+
return nil unless style_index?(style_index)
|
|
473
473
|
|
|
474
474
|
precompute! unless @format_codes
|
|
475
475
|
@format_codes[style_index]
|
|
@@ -482,7 +482,7 @@ module Xlsxrb
|
|
|
482
482
|
# @api public
|
|
483
483
|
#: (Integer? style_index) -> Symbol?
|
|
484
484
|
def format_type(style_index)
|
|
485
|
-
return nil unless style_index
|
|
485
|
+
return nil unless style_index?(style_index)
|
|
486
486
|
|
|
487
487
|
precompute! unless @format_types
|
|
488
488
|
@format_types[style_index]
|
|
@@ -495,7 +495,7 @@ module Xlsxrb
|
|
|
495
495
|
# @api public
|
|
496
496
|
#: (Integer? style_index) -> bool
|
|
497
497
|
def date_format?(style_index)
|
|
498
|
-
return false unless style_index
|
|
498
|
+
return false unless style_index?(style_index)
|
|
499
499
|
|
|
500
500
|
precompute! unless @date_flags
|
|
501
501
|
@date_flags[style_index] || false
|
|
@@ -508,7 +508,7 @@ module Xlsxrb
|
|
|
508
508
|
# @api public
|
|
509
509
|
#: (Integer? style_index) -> bool
|
|
510
510
|
def datetime_format?(style_index)
|
|
511
|
-
return false unless style_index
|
|
511
|
+
return false unless style_index?(style_index)
|
|
512
512
|
|
|
513
513
|
precompute! unless @datetime_flags
|
|
514
514
|
@datetime_flags[style_index] || false
|
|
@@ -521,7 +521,7 @@ module Xlsxrb
|
|
|
521
521
|
# @api public
|
|
522
522
|
#: (Integer? style_index) -> bool
|
|
523
523
|
def time_format?(style_index)
|
|
524
|
-
return false unless style_index
|
|
524
|
+
return false unless style_index?(style_index)
|
|
525
525
|
|
|
526
526
|
precompute! unless @time_flags
|
|
527
527
|
@time_flags[style_index] || false
|
|
@@ -563,7 +563,9 @@ module Xlsxrb
|
|
|
563
563
|
num_fmt_id = xf.is_a?(Elements::CellXf) ? xf.num_fmt_id : xf[:num_fmt_id]
|
|
564
564
|
xf_id = xf.is_a?(Elements::CellXf) ? xf.xf_id : xf[:xf_id]
|
|
565
565
|
if (num_fmt_id.nil? || num_fmt_id.zero?) && xf_id && cs_xfs.is_a?(Array)
|
|
566
|
-
|
|
566
|
+
# An xfId outside the array names no parent. Array#[] would count a negative
|
|
567
|
+
# one from the end and raise RangeError for one that does not fit in a word.
|
|
568
|
+
parent_xf = xf_id.is_a?(Integer) && xf_id.between?(0, cs_xfs.size - 1) ? cs_xfs[xf_id] : nil
|
|
567
569
|
if parent_xf.is_a?(Elements::CellXf)
|
|
568
570
|
num_fmt_id = parent_xf.num_fmt_id
|
|
569
571
|
elsif parent_xf.is_a?(Hash)
|
|
@@ -592,6 +594,13 @@ module Xlsxrb
|
|
|
592
594
|
|
|
593
595
|
private
|
|
594
596
|
|
|
597
|
+
# Whether +value+ can be an index into cellXfs. A larger Integer is not one, and
|
|
598
|
+
# Array#[] raises RangeError for an Integer that does not fit in a machine word.
|
|
599
|
+
#: (untyped value) -> bool
|
|
600
|
+
def style_index?(value)
|
|
601
|
+
value.is_a?(Integer) && value.between?(0, 0x7FFFFFFF)
|
|
602
|
+
end
|
|
603
|
+
|
|
595
604
|
def next_num_fmt_id
|
|
596
605
|
max_id = [163, *number_formats.keys].max
|
|
597
606
|
max_id + 1
|
|
@@ -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
|
|
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
|
|
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")
|
|
@@ -17,6 +17,14 @@ module Xlsxrb
|
|
|
17
17
|
"mm-dd-yy", "d-mmm-yy", "d-mmm", "mmm-yy", "h:mm AM/PM", "h:mm:ss AM/PM", "h:mm", "h:mm:ss", "m/d/yy h:mm", "mm:ss", "[h]:mm:ss", "mmss.0"
|
|
18
18
|
].freeze
|
|
19
19
|
|
|
20
|
+
# Excel accepts format codes of up to 255 characters. Longer codes are not applied: the
|
|
21
|
+
# cost of formatting grows with the code, for every cell that uses it.
|
|
22
|
+
MAX_FORMAT_CODE_LENGTH = 1024
|
|
23
|
+
|
|
24
|
+
# Stands for a literal "%" while a date format code is converted to a strftime pattern.
|
|
25
|
+
LITERAL_PERCENT = "\x01"
|
|
26
|
+
private_constant :LITERAL_PERCENT
|
|
27
|
+
|
|
20
28
|
class << self
|
|
21
29
|
# Formats a cell value according to an Excel format code string.
|
|
22
30
|
#
|
|
@@ -32,17 +40,24 @@ module Xlsxrb
|
|
|
32
40
|
return value ? "TRUE" : "FALSE" if [true, false].include?(value)
|
|
33
41
|
|
|
34
42
|
code = format_code.to_s.strip
|
|
35
|
-
return default_format(value) if code.empty? || code.casecmp("general").zero?
|
|
43
|
+
return default_format(value) if code.empty? || code.casecmp("general").zero? || code.length > MAX_FORMAT_CODE_LENGTH
|
|
44
|
+
# Infinity and NaN, from values such as 1e999, have no date or digits to format.
|
|
45
|
+
return value.to_s if value.is_a?(Float) && !value.finite?
|
|
36
46
|
|
|
37
47
|
return format_datetime(value, code) if value.is_a?(Date) || value.is_a?(DateTime) || value.is_a?(Time)
|
|
38
48
|
|
|
39
49
|
if value.is_a?(Numeric) && date_format?(code)
|
|
40
|
-
dt =
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
50
|
+
dt = begin
|
|
51
|
+
if value.is_a?(Float) && (value % 1).positive?
|
|
52
|
+
Ooxml::Utils.serial_to_datetime(value, date1904: date1904)
|
|
53
|
+
else
|
|
54
|
+
Ooxml::Utils.serial_to_date(value.to_i, date1904: date1904)
|
|
55
|
+
end
|
|
56
|
+
rescue ArgumentError, RangeError
|
|
57
|
+
# A serial number outside the dates Excel supports.
|
|
58
|
+
nil
|
|
59
|
+
end
|
|
60
|
+
return dt ? format_datetime(dt, code) : default_format(value)
|
|
46
61
|
end
|
|
47
62
|
|
|
48
63
|
return format_number(value, code) if value.is_a?(Numeric)
|
|
@@ -380,7 +395,9 @@ module Xlsxrb
|
|
|
380
395
|
end
|
|
381
396
|
|
|
382
397
|
def excel_to_strftime(format_code)
|
|
383
|
-
code
|
|
398
|
+
# A "%" in the format code is literal text. Left as is, it would be read by strftime
|
|
399
|
+
# as a directive, and "%999999d" asks for a field of 999,999 characters.
|
|
400
|
+
code = format_code.delete(LITERAL_PERCENT).gsub("%", LITERAL_PERCENT)
|
|
384
401
|
|
|
385
402
|
code.gsub!(%r{am/pm}i, "%p")
|
|
386
403
|
code.gsub!(%r{a/p}i, "%p")
|
|
@@ -421,6 +438,7 @@ module Xlsxrb
|
|
|
421
438
|
code.gsub!(/yy/i, "%y")
|
|
422
439
|
|
|
423
440
|
code.gsub!(/\\(.)/, "\\1")
|
|
441
|
+
code.gsub!(LITERAL_PERCENT, "%%")
|
|
424
442
|
|
|
425
443
|
code
|
|
426
444
|
end
|
data/lib/xlsxrb/ooxml/cfb.rb
CHANGED
|
@@ -125,12 +125,16 @@ module Xlsxrb
|
|
|
125
125
|
@header_difat = @data[0x4C, 436].unpack("V109").reject { |s| [FREESECT, ENDOFCHAIN].include?(s) }
|
|
126
126
|
end
|
|
127
127
|
|
|
128
|
+
# The header takes the first sector: 512 bytes in version 3, and 4,096 in version 4,
|
|
129
|
+
# where it is padded with zeros. Sector 0 follows it.
|
|
128
130
|
def sector_offset(sector_id)
|
|
129
|
-
|
|
131
|
+
(sector_id + 1) * @sector_size
|
|
130
132
|
end
|
|
131
133
|
|
|
132
134
|
def read_sector(sector_id)
|
|
133
|
-
|
|
135
|
+
# The last sector may be shorter than a sector: Excel 2007 ends some files where
|
|
136
|
+
# the last stream ends, without padding.
|
|
137
|
+
max_sectors = ((@data.bytesize + @sector_size - 1) / @sector_size) - 1
|
|
134
138
|
return "".b if sector_id.negative? || sector_id >= max_sectors
|
|
135
139
|
|
|
136
140
|
offset = sector_offset(sector_id)
|
|
@@ -158,11 +162,15 @@ module Xlsxrb
|
|
|
158
162
|
end
|
|
159
163
|
end
|
|
160
164
|
|
|
161
|
-
# Read all FAT sectors
|
|
165
|
+
# Read all FAT sectors. Each may be listed once: a DIFAT that repeats a sector
|
|
166
|
+
# would otherwise grow the FAT far beyond the size of the file.
|
|
162
167
|
@fat = []
|
|
168
|
+
loaded = {}
|
|
163
169
|
@difat_sectors.each do |fat_sec_id|
|
|
164
170
|
break if [ENDOFCHAIN, FREESECT].include?(fat_sec_id)
|
|
171
|
+
raise Xlsxrb::Error, "Invalid CFB file: FAT sector #{fat_sec_id} is listed more than once" if loaded[fat_sec_id]
|
|
165
172
|
|
|
173
|
+
loaded[fat_sec_id] = true
|
|
166
174
|
sec_data = read_sector(fat_sec_id)
|
|
167
175
|
@fat.concat(sec_data.unpack("V*"))
|
|
168
176
|
end
|
|
@@ -41,7 +41,10 @@ module Xlsxrb
|
|
|
41
41
|
k_ver_val = derive_key(digest, h_final, BLOCK_KEY_VERIFIER_VALUE, key_bytes)
|
|
42
42
|
decrypted_hash = aes_decrypt(cipher_name, k_ver_val, info[:encryptor_salt], info[:encrypted_verifier_hash_value])
|
|
43
43
|
|
|
44
|
+
# A hashSize shorter than the digest would compare fewer bytes, and 0 would accept
|
|
45
|
+
# any password.
|
|
44
46
|
hash_size = info[:hash_size]
|
|
47
|
+
raise Xlsxrb::DecryptionError, "Invalid hashSize in EncryptionInfo: #{hash_size}" unless hash_size == digest.digest_length
|
|
45
48
|
raise Xlsxrb::InvalidPasswordError, "Password verification failed" unless OpenSSL.secure_compare(decrypted_hash[0, hash_size], expected_hash[0, hash_size])
|
|
46
49
|
|
|
47
50
|
# 3. Decrypt package master key
|
|
@@ -60,6 +63,9 @@ module Xlsxrb
|
|
|
60
63
|
pkg_digest = digest_for(info[:key_data_hash_algorithm])
|
|
61
64
|
pkg_salt = info[:key_data_salt]
|
|
62
65
|
|
|
66
|
+
# 5. Check the HMAC of the stream before decrypting it
|
|
67
|
+
intact = integrity_verified?(info, pkg_cipher_name, pkg_digest, package_key, encrypted_package_bytes)
|
|
68
|
+
|
|
63
69
|
decrypted = +""
|
|
64
70
|
num_blocks = (encrypted_data.bytesize + SEGMENT_SIZE - 1) / SEGMENT_SIZE
|
|
65
71
|
num_blocks.times do |i|
|
|
@@ -70,7 +76,10 @@ module Xlsxrb
|
|
|
70
76
|
decrypted << aes_decrypt_block(pkg_cipher_name, package_key, iv, chunk)
|
|
71
77
|
end
|
|
72
78
|
|
|
73
|
-
decrypted[0, total_size] || "".b
|
|
79
|
+
plain = decrypted[0, total_size] || "".b
|
|
80
|
+
raise Xlsxrb::DecryptionError, "Data integrity check failed: the encrypted package does not match its HMAC" unless intact || legacy_integrity_verified?(info, cipher_name, digest, h_final, plain)
|
|
81
|
+
|
|
82
|
+
plain
|
|
74
83
|
end
|
|
75
84
|
|
|
76
85
|
# Encrypts a plain zip payload with the given password into EncryptionInfo and EncryptedPackage streams.
|
|
@@ -126,15 +135,13 @@ module Xlsxrb
|
|
|
126
135
|
encrypted_package_stream << aes_encrypt_block(cipher_name, package_key, iv, chunk)
|
|
127
136
|
end
|
|
128
137
|
|
|
129
|
-
# Data integrity HMAC
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
encrypted_hmac_key = aes_encrypt(cipher_name,
|
|
135
|
-
|
|
136
|
-
k_integ_val = derive_key(digest, h_final, BLOCK_KEY_INTEGRITY_VALUE, key_bytes)
|
|
137
|
-
encrypted_hmac_val = aes_encrypt(cipher_name, k_integ_val, encryptor_salt, hmac_value)
|
|
138
|
+
# Data integrity ([MS-OFFCRYPTO] 2.3.4.14): an HMAC of the whole EncryptedPackage
|
|
139
|
+
# stream, its size prefix included. The HMAC key and value are encrypted with the
|
|
140
|
+
# package key, each with an IV derived from the keyData salt.
|
|
141
|
+
hmac_key = SecureRandom.random_bytes(hash_size)
|
|
142
|
+
hmac_value = OpenSSL::HMAC.digest(hash_algorithm, hmac_key, encrypted_package_stream)
|
|
143
|
+
encrypted_hmac_key = aes_encrypt(cipher_name, package_key, digest.digest(key_data_salt + BLOCK_KEY_INTEGRITY_KEY), hmac_key)
|
|
144
|
+
encrypted_hmac_val = aes_encrypt(cipher_name, package_key, digest.digest(key_data_salt + BLOCK_KEY_INTEGRITY_VALUE), hmac_value)
|
|
138
145
|
|
|
139
146
|
# Build EncryptionInfo XML
|
|
140
147
|
xml = <<~XML
|
|
@@ -185,12 +192,15 @@ module Xlsxrb
|
|
|
185
192
|
raise Xlsxrb::DecryptionError, "spinCount out of allowed bounds: #{spin_count}" if spin_count.negative? || spin_count > 10_000_000
|
|
186
193
|
|
|
187
194
|
key_attrs = key_data&.attributes
|
|
195
|
+
integrity_attrs = root.elements["dataIntegrity"]&.attributes
|
|
188
196
|
{
|
|
189
197
|
key_data_salt: key_attrs&.[]("saltValue").to_s.unpack1("m0") || "".b,
|
|
190
198
|
key_data_hash_algorithm: key_attrs&.[]("hashAlgorithm") || "SHA512",
|
|
191
199
|
key_data_cipher_algorithm: key_attrs&.[]("cipherAlgorithm") || "AES",
|
|
192
200
|
key_data_key_bits: key_attrs&.[]("keyBits")&.to_i || 256,
|
|
193
201
|
key_data_block_size: key_attrs&.[]("blockSize")&.to_i || 16,
|
|
202
|
+
encrypted_hmac_key: integrity_attrs&.[]("encryptedHmacKey")&.unpack1("m0"),
|
|
203
|
+
encrypted_hmac_value: integrity_attrs&.[]("encryptedHmacValue")&.unpack1("m0"),
|
|
194
204
|
|
|
195
205
|
spin_count: spin_count,
|
|
196
206
|
encryptor_salt: key_encryptor.attributes["saltValue"].to_s.unpack1("m0") || "".b,
|
|
@@ -204,6 +214,32 @@ module Xlsxrb
|
|
|
204
214
|
}
|
|
205
215
|
end
|
|
206
216
|
|
|
217
|
+
# Data integrity ([MS-OFFCRYPTO] 2.3.4.14): the HMAC of the whole EncryptedPackage
|
|
218
|
+
# stream. The HMAC key and value are encrypted with the package key, each with an
|
|
219
|
+
# IV derived from the keyData salt.
|
|
220
|
+
def integrity_verified?(info, cipher_name, digest, package_key, encrypted_package_bytes)
|
|
221
|
+
encrypted_key = info[:encrypted_hmac_key]
|
|
222
|
+
encrypted_value = info[:encrypted_hmac_value]
|
|
223
|
+
raise Xlsxrb::DecryptionError, "Missing dataIntegrity in EncryptionInfo" if encrypted_key.nil? || encrypted_value.nil?
|
|
224
|
+
|
|
225
|
+
salt = info[:key_data_salt]
|
|
226
|
+
size = digest.digest_length
|
|
227
|
+
hmac_key = aes_decrypt(cipher_name, package_key, digest.digest(salt + BLOCK_KEY_INTEGRITY_KEY), encrypted_key)[0, size]
|
|
228
|
+
hmac_value = aes_decrypt(cipher_name, package_key, digest.digest(salt + BLOCK_KEY_INTEGRITY_VALUE), encrypted_value)[0, size]
|
|
229
|
+
OpenSSL.secure_compare(OpenSSL::HMAC.digest(digest.name, hmac_key, encrypted_package_bytes), hmac_value)
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
# xlsxrb 0.2.1 and earlier wrote an HMAC of the package before encryption, with the HMAC
|
|
233
|
+
# key and value encrypted under keys derived from the password. Files it wrote are
|
|
234
|
+
# still read; this HMAC also fails for a package that was changed.
|
|
235
|
+
def legacy_integrity_verified?(info, cipher_name, digest, h_final, plain)
|
|
236
|
+
key_bytes = info[:key_bits] / 8
|
|
237
|
+
salt = info[:encryptor_salt]
|
|
238
|
+
hmac_key = aes_decrypt(cipher_name, derive_key(digest, h_final, BLOCK_KEY_INTEGRITY_KEY, key_bytes), salt, info[:encrypted_hmac_key])
|
|
239
|
+
hmac_value = aes_decrypt(cipher_name, derive_key(digest, h_final, BLOCK_KEY_INTEGRITY_VALUE, key_bytes), salt, info[:encrypted_hmac_value])
|
|
240
|
+
OpenSSL.secure_compare(OpenSSL::HMAC.digest(digest.name, hmac_key, plain), hmac_value)
|
|
241
|
+
end
|
|
242
|
+
|
|
207
243
|
def digest_for(name)
|
|
208
244
|
case name.to_s.upcase.gsub(/[^A-Z0-9]/, "")
|
|
209
245
|
when "SHA512" then OpenSSL::Digest.new("SHA512")
|
|
@@ -218,6 +254,8 @@ module Xlsxrb
|
|
|
218
254
|
def cipher_name_for(algo, key_bits)
|
|
219
255
|
case algo.to_s.upcase
|
|
220
256
|
when "AES"
|
|
257
|
+
raise Xlsxrb::DecryptionError, "Unsupported AES key size: #{key_bits}" unless [128, 192, 256].include?(key_bits)
|
|
258
|
+
|
|
221
259
|
"aes-#{key_bits}-cbc"
|
|
222
260
|
else
|
|
223
261
|
raise Xlsxrb::DecryptionError, "Unsupported cipher algorithm: #{algo}"
|
|
@@ -35,7 +35,11 @@ module Xlsxrb
|
|
|
35
35
|
total_size = encrypted_package_bytes[0, 8].unpack1("Q<")
|
|
36
36
|
raise Xlsxrb::DecryptionError, "Encrypted package size is invalid or exceeds limits" if total_size.negative? || total_size > 0x400_000_000
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
# Only the blocks that hold the package are decrypted. Some writers leave bytes
|
|
39
|
+
# after them that are not a whole block.
|
|
40
|
+
encrypted_size = (total_size + 15) / 16 * 16
|
|
41
|
+
encrypted_data = encrypted_package_bytes[8, encrypted_size] || "".b
|
|
42
|
+
raise Xlsxrb::DecryptionError, "Encrypted package is shorter than its declared size" if encrypted_data.bytesize < encrypted_size
|
|
39
43
|
|
|
40
44
|
decrypted = aes_ecb_decrypt(k, encrypted_data)
|
|
41
45
|
decrypted[0, total_size] || "".b
|
data/lib/xlsxrb/ooxml/crypto.rb
CHANGED
|
@@ -41,6 +41,9 @@ module Xlsxrb
|
|
|
41
41
|
else
|
|
42
42
|
raise Xlsxrb::DecryptionError, "Unsupported encryption version #{major}.#{minor}"
|
|
43
43
|
end
|
|
44
|
+
rescue OpenSSL::OpenSSLError, ArgumentError => e
|
|
45
|
+
# Salts, keys, and ciphertext of the wrong length, and invalid Base64.
|
|
46
|
+
raise Xlsxrb::DecryptionError, "Malformed encrypted package: #{e.message}"
|
|
44
47
|
end
|
|
45
48
|
|
|
46
49
|
# Encrypts a plain ZIP payload with the given password into an encrypted CFB package.
|