oxcel 0.1.0-x86_64-linux

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b6986059346a89c7c324e8394034e88bc857cd85478bf190653807195d015b12
4
+ data.tar.gz: 4caad153897e8a5fde4a4150271fb429c0a6efdf9e94b77c68fe3b06eacf1392
5
+ SHA512:
6
+ metadata.gz: dad7964f207f28601a487bfc2b9eaf3cdf2945920fc829460a4df215b1938540bdc7b01e93fff203beb3cd58597ba55595cedd6e9ca7b414132f2caba359596f
7
+ data.tar.gz: 215e1c3e2d272ac14cc0944657e3bc5f1313682e28e7aa841d36795e53f98301d40fd250cb575b8ae616753fcd94f57a1c17456d91b59e3a35e7d41d49c02391
data/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ ## [0.1.0] - 2026-12-06
6
+
7
+ - Initial release combining Rust's `calamine` 0.39 and `rust_xlsxwriter` 0.105 with zero non-native Ruby dependencies.
8
+ - **True O(1) `.xlsx` streaming reader** via `XlsxCellReader` (zero-copy `SharedString`, `Enumerable` inclusion, lazy `Enumerator#first` early-break support, deterministic `Reader#close` / `closed?` auto-closed on block exit, ~30 MB flat Peak RSS on 100k rows).
9
+ - **Alba-inspired declarative `Oxcel::Resource` DSL** with pre-compiled extractors, `columns` shorthand, conditional columns (`if:`), `params:`, `after_write` hooks (e.g. `SUM` total rows), `save`/`to_file`/`to_bytes`, multi-sheet composition (`write_to`), and batched constant-memory streaming.
10
+ - **Global configuration (`Oxcel.configure` / `Oxcel.config`)** for `coerce_integers`, `constant_memory`, `default_date_format`, and `default_datetime_format`.
11
+ - **Native Ruby types & utilities**: `Integer`, `Float`, `BigDecimal`, `Date` vs `Time` distinction, `Boolean`, `Oxcel.formula`, `Oxcel.link`, `Oxcel.cell`, `Oxcel::A1` coordinate helpers, value-object equality (`==`/`eql?`/`hash`), and readable `#inspect`.
12
+ - **Reader metadata & flexibility**: `sheets_metadata`, `merged_regions`, `formulas` (sparse coordinate hash), `dimensions`, `Oxcel.open_bytes`, `IO`/`StringIO`/`Pathname`/extensionless `Tempfile` auto-detection, explicit `format:`.
13
+ - **B2B report writer features**: `page_setup` (landscape/portrait, A4/A3/Letter/B4/B5, `fit_to_pages`, `repeat_rows`, header/footer, print gridlines), `column_width`, `add_dropdown`, `add_note`, `protect`, `tab_color`, `gridlines`, individual borders, underline/strikethrough/indent/rotation/shrink/valign, `merge_range`, `autofilter`, `freeze_panes`, `autofit`.
14
+ - **Zero-config Rails 7/8 Railtie**: auto-loaded when Rails is present; registers `:xlsx` MIME type and `render xlsx:` supporting both `Oxcel::Resource` and procedural builders.
15
+ - **Migration toolkit** (lazy-loaded via `autoload`): `Oxcel::Compat::Caxlsx`, `Oxcel::Compat::Roo`, O(1) streaming `Oxcel.diff`, and migration guides (`docs/MIGRATING_FROM_CAXLSX.md`, `docs/MIGRATING_FROM_ROO.md`).
16
+ - **First-party type definitions & Agent Skill**: bundled Sorbet / Tapioca `rbi/oxcel.rbi`, Ruby `sig/oxcel.rbs` (guarded by reflection drift tests), and `skills/oxcel/SKILL.md`.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ken3ypa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,212 @@
1
+ <div align="center">
2
+
3
+ # oxcel
4
+
5
+ **Blazing-fast, flat-memory Excel (`.xlsx`, `.xlsm`, `.xlsb`, `.xls`, `.ods`) reader & writer for Ruby — powered by Rust (`calamine` + `rust_xlsxwriter`).**
6
+
7
+ *True O(1) Streaming Read · Constant-Memory Write · Alba-Style Resource DSL · Sorbet & RBS Types*
8
+
9
+ [![CI](https://img.shields.io/github/actions/workflow/status/ken3ypa/oxcel/ci.yml?branch=main&style=for-the-badge&label=CI)](https://github.com/ken3ypa/oxcel/actions/workflows/ci.yml)
10
+ [![Release](https://img.shields.io/github/v/release/ken3ypa/oxcel?style=for-the-badge&label=Release)](https://github.com/ken3ypa/oxcel/releases)
11
+ [![Ruby](https://img.shields.io/badge/Ruby-%3E%3D%203.2-CC342D?style=for-the-badge&logo=ruby&logoColor=white)](https://www.ruby-lang.org/)
12
+ [![License: MIT](https://img.shields.io/github/license/ken3ypa/oxcel?style=for-the-badge)](LICENSE.txt)
13
+
14
+ <p>
15
+ <a href="#why-oxcel">Why Oxcel</a> ·
16
+ <a href="#benchmarks-100000-rows--6-cols">Benchmarks</a> ·
17
+ <a href="#installation">Install</a> ·
18
+ <a href="#quickstart">Quickstart</a> ·
19
+ <a href="#migrating-from-caxlsx--roo">Migrating</a> ·
20
+ <a href="#type-definitions-sorbet--tapioca--rbs">Types</a> ·
21
+ <a href="CHANGELOG.md">Changelog</a>
22
+ </p>
23
+
24
+ </div>
25
+
26
+ > **Status:** Early `v0.1` release. The public API may evolve before `1.0`.
27
+
28
+ ## Why Oxcel?
29
+
30
+ | Capability | `oxcel` | `caxlsx` | `roo` | `fast_excel` | `fast_xlsx` / `calx` |
31
+ |---|---|---|---|---|---|
32
+ | **Read + Write in one gem** | **Yes** | Write only | Read only | Write only | Separate gems |
33
+ | **Constant-memory XLSX write** | **Yes (~30 MB flat)** | No (DOM in RAM) | — | Yes | `fast_xlsx` |
34
+ | **True O(1) streaming XLSX read** | **Yes (~30 MB flat)** | — | Streaming XML (slow) | — | `calx` |
35
+ | **Declarative Resource DSL (Alba-style)** | **Yes (`Oxcel::Resource`)** | No | No | No | No |
36
+ | **Precompiled native gems (no Rust/C needed)** | **Yes (7 platforms)** | Pure Ruby | Pure Ruby | Compiles C | Yes |
37
+ | **B2B Print / Dropdown / Notes / Borders** | **Yes** | Partial | — | Partial | `fast_xlsx` |
38
+ | **Rails 8 Railtie (`render xlsx:`)** | **Yes** | Separate gem | No | No | No |
39
+
40
+ ## Benchmarks (100,000 rows × 6 cols)
41
+
42
+ Measured in **isolated child processes** (`getrusage` OS `ru_maxrss`) on Ruby 4.0.10 (`arm64-darwin25`). Reproducible via `ROWS=100000 bundle exec ruby -Ilib bench/benchmark.rb`.
43
+
44
+ ### Write (100,000 rows × 6 cols, Japanese + ASCII mixed)
45
+
46
+ | Library | Wall Time | Peak RSS | Ruby Allocations | vs `caxlsx` |
47
+ |---|---:|---:|---:|---|
48
+ | **`Oxcel.write` (`constant_memory: true`)** | **0.300s** | **30.1 MB** | 900k | **15.8x faster / 5.5x less RAM** |
49
+ | **`Oxcel::Resource` (declarative DSL)** | **0.364s** | **30.2 MB** | 1.00M | **13.0x faster / 5.5x less RAM** |
50
+ | `caxlsx` 4.5 (pure Ruby) | 4.720s | 166.9 MB | 5.19M | baseline |
51
+
52
+ ### Read (100,000 rows × 6 cols)
53
+
54
+ | Library | Wall Time | Peak RSS | Ruby Allocations | vs `roo` |
55
+ |---|---:|---:|---:|---|
56
+ | **`Oxcel.each_row` (O(1) `.xlsx` stream)** | **0.155s** | **30.6 MB** | 400k | **35.9x faster / 6.1x less RAM** |
57
+ | `roo` 4.0 (`each_row_streaming`) | 5.568s | 186.5 MB | 19.96M | baseline |
58
+
59
+ ---
60
+
61
+ ## Installation
62
+
63
+ Add `oxcel` to your `Gemfile`:
64
+
65
+ ```ruby
66
+ gem "oxcel"
67
+ ```
68
+
69
+ Precompiled native gems are built for 7 platforms (`arm64-darwin`, `x86_64-darwin`, `x86_64-linux`, `aarch64-linux`, `x86_64-linux-musl`, `aarch64-linux-musl`, `x64-mingw-ucrt`) across Ruby 3.2–4.0, so no Rust toolchain is required at install time.
70
+
71
+ ## Quickstart
72
+
73
+ ### 1. Declarative Export (`Oxcel::Resource`, Alba-style)
74
+
75
+ Define reusable, testable Excel exporters with pre-compiled column extractors, conditional columns, print setup, and batched constant-memory streaming:
76
+
77
+ ```ruby
78
+ class OrderExporter
79
+ include Oxcel::Resource
80
+
81
+ sheet_name "注文一覧"
82
+ constant_memory true
83
+ freeze_header true
84
+ autofilter true
85
+ header_height 24
86
+ header_style bold: true, bg_color: "#1F4E78", font_color: "#FFFFFF", align: :center
87
+ page_setup orientation: :landscape, paper_size: :a4, fit_to_pages: [1, 0], repeat_rows: [0, 0]
88
+
89
+ column :id, header: "ID", width: 10
90
+ column :customer, header: "顧客名", width: 24 do |order|
91
+ order.customer_name
92
+ end
93
+ column :amount, header: "金額", width: 14, num_format: "#,##0", align: :right
94
+ column :ordered_on, header: "注文日", width: 14, num_format: "yyyy/mm/dd"
95
+ column :secret, header: "内部メモ", if: ->(params) { params[:admin] }
96
+
97
+ after_write do |sheet|
98
+ sheet.add_row(["合計", nil, Oxcel.formula("=SUM(C2:C#{sheet.row_count})")])
99
+ end
100
+ end
101
+
102
+ # Stream ActiveRecord batches directly to disk or memory
103
+ OrderExporter.new(Order.find_each, params: { admin: true }).save("orders.xlsx")
104
+ bytes = OrderExporter.new(Order.find_each).to_bytes
105
+
106
+ # Compose multiple Resources into a single multi-sheet workbook
107
+ Oxcel.write("monthly_report.xlsx", constant_memory: true) do |wb|
108
+ OrderExporter.new(Order.find_each).write_to(wb)
109
+ SummaryExporter.new(summaries).write_to(wb)
110
+ end
111
+ ```
112
+
113
+ ### 2. Rails Integration & Global Configuration
114
+
115
+ When Rails is present, `oxcel` automatically registers its Railtie (zero initializer boilerplate):
116
+
117
+ ```ruby
118
+ # Optional global defaults (e.g. config/initializers/oxcel.rb)
119
+ Oxcel.configure do |config|
120
+ config.coerce_integers = true
121
+ config.default_date_format = "yyyy/mm/dd"
122
+ config.default_datetime_format = "yyyy/mm/dd hh:mm:ss"
123
+ end
124
+
125
+ class OrdersController < ApplicationController
126
+ def export
127
+ render xlsx: OrderExporter.new(Order.find_each), filename: "orders_2026.xlsx"
128
+ end
129
+ end
130
+ ```
131
+
132
+ ### 3. True O(1) Streaming Read (Files, `IO`, `StringIO`, ActiveStorage Bytes)
133
+
134
+ ```ruby
135
+ # Lazy O(1) streaming — stops parsing immediately after 10 rows!
136
+ Oxcel.each_row("huge_1m_rows.xlsx", coerce_integers: true).first(10)
137
+
138
+ # Stream as hashes with symbolized keys (supports .xlsx, .xlsm, .xlsb, .xls, .ods)
139
+ Oxcel.each_hash("orders.xlsx", coerce_integers: true, symbolize_keys: true) do |row|
140
+ # Native Ruby Date / Time / Integer / Float / Boolean / String
141
+ puts "#{row[:id]}: #{row[:ordered_on].class}" # => Date
142
+ end
143
+
144
+ # Read directly from memory or uploaded Tempfile (even without .xlsx extension)
145
+ Oxcel.open_bytes(blob.download) do |reader|
146
+ reader.sheets_metadata # => [{ name: "注文一覧", visibility: :visible, type: :worksheet }]
147
+ reader.merged_regions # => [[0, 0, 0, 5]]
148
+ reader.formulas # => { [4, 2] => "SUM(C3:C4)" }
149
+ end
150
+ ```
151
+
152
+ ### 4. Low-Level Procedural Writer & B2B Report Features
153
+
154
+ ```ruby
155
+ Oxcel.write("invoice.xlsx") do |wb|
156
+ header = wb.add_style(bold: true, bg_color: "#1F4E78", font_color: "#FFFFFF", border_bottom: :double)
157
+ money = wb.add_style(num_format: "#,##0", align: :right)
158
+
159
+ wb.add_sheet("請求書") do |s|
160
+ s.tab_color("#1F4E78")
161
+ s.page_setup(orientation: :landscape, paper_size: :a4, fit_to_pages: [1, 0], header: "&C御請求書", footer: "&R&P / &N")
162
+ s.merge_range(0, 0, 0, 3, "2026年12月 請求書", style: header)
163
+ s.add_row(%w[品目 ステータス 金額 リンク], style: header)
164
+ s.add_row(["保守費用", "未払い", 50_000, Oxcel.link("https://example.com", "詳細")], styles: [nil, nil, money, nil])
165
+ s.add_row(["合計", nil, Oxcel.formula("=SUM(C3:C3)"), nil], styles: [nil, nil, money, nil])
166
+ s.add_note(2, 0, "月末締め")
167
+ s.add_dropdown(2, 1, 20, 1, %w[未払い 支払済 保留])
168
+ s.protect(password: "secret")
169
+ end
170
+ end
171
+ ```
172
+
173
+ ---
174
+
175
+ ## Migrating from `caxlsx` / `roo`
176
+
177
+ `oxcel` includes a full migration toolkit so existing codebases can switch incrementally with zero guesswork:
178
+
179
+ - **Drop-in compatibility adapters** (opt-in):
180
+ - `require "oxcel/compat/caxlsx"` → `Oxcel::Compat::Caxlsx::Package` (`workbook`, `styles.add_style`, `add_worksheet`, `add_row(..., types:, style:, height:)`, `merge_cells("A1:D1")`, `auto_filter=`, `sheet_view.pane`, `serialize`, `to_stream`)
181
+ - `require "oxcel/compat/roo"` → `Oxcel::Compat::Roo::Excelx` & `Spreadsheet.open` (1-indexed `row(n)`, `cell(r, c)`, `first_row`/`last_row`, O(1) `each_row_streaming`, Roo 4.0-compatible `parse(headers: true)`)
182
+ - **O(1) Streaming Workbook Diff (`Oxcel.diff`)**: Compare legacy `caxlsx` vs new `oxcel` workbooks cell-by-cell in tests or shadow runs:
183
+ ```ruby
184
+ result = Oxcel.diff("legacy_caxlsx.xlsx", "new_oxcel.xlsx", tolerance: 1e-9)
185
+ raise result.to_s if result.different?
186
+ ```
187
+ - **Step-by-step guides**:
188
+ - [Migrating from `caxlsx`](docs/MIGRATING_FROM_CAXLSX.md)
189
+ - [Migrating from `roo`](docs/MIGRATING_FROM_ROO.md)
190
+
191
+ ## Type Definitions (Sorbet / Tapioca & RBS)
192
+
193
+ `oxcel` ships first-party type definitions with zero runtime dependencies (no `sorbet-runtime` required):
194
+
195
+ - **Sorbet / Tapioca (`rbi/oxcel.rbi`)**: Bundled in the gem so `bin/tapioca gem oxcel` automatically imports strict Sorbet signatures for `Oxcel`, `Oxcel::Resource` (with `mixes_in_class_methods`), `Oxcel.diff`, and `Oxcel::Compat::*`.
196
+ - **RBS / Steep / Ruby LSP (`sig/oxcel.rbs`)**: Standard RBS signatures validated against Ruby's `rbs` CLI.
197
+
198
+ ## Agent Skill
199
+
200
+ This repository bundles an Agent Skill at [`skills/oxcel/SKILL.md`](skills/oxcel/SKILL.md) so AI coding agents can write `Oxcel::Resource` exporters, streaming readers, and `caxlsx`/`roo` migrations accurately.
201
+
202
+ ## Development
203
+
204
+ ```bash
205
+ bundle install
206
+ bundle exec rake test
207
+ cargo clippy --manifest-path ext/oxcel/Cargo.toml -- -D warnings
208
+ rbs -r date -r time -I sig validate
209
+ ROWS=100000 bundle exec ruby -Ilib bench/benchmark.rb
210
+ ```
211
+
212
+ See [CONTRIBUTING.md](CONTRIBUTING.md), [SECURITY.md](SECURITY.md), and [CHANGELOG.md](CHANGELOG.md).
@@ -0,0 +1,120 @@
1
+ # Migrating from `caxlsx` (`axlsx`) to `oxcel`
2
+
3
+ `oxcel` replaces `caxlsx`'s in-memory DOM writer with Rust's `rust_xlsxwriter` (`constant_memory: true`), cutting peak RSS to a flat ~30 MB and speeding up 100k-row exports by ~15x.
4
+
5
+ You can migrate in **two safe phases**:
6
+
7
+ 1. **Phase 1 (Drop-in adapter + diff verification)**: Switch to `Oxcel::Compat::Caxlsx::Package` and verify parity against your existing `caxlsx` output with `Oxcel.diff`.
8
+ 2. **Phase 2 (Idiomatic Oxcel)**: Move to `Oxcel.write` / `Oxcel::Resource` for declarative exporters, batched FFI streaming (`add_rows` / `stream`), and full B2B formatting.
9
+
10
+ ---
11
+
12
+ ## Phase 1: Drop-in Adapter (`Oxcel::Compat::Caxlsx`)
13
+
14
+ Require the opt-in adapter and swap `Axlsx::Package` for `Oxcel::Compat::Caxlsx::Package`:
15
+
16
+ ```ruby
17
+ # Before (caxlsx)
18
+ require "axlsx"
19
+
20
+ package = Axlsx::Package.new
21
+ package.use_shared_strings = true
22
+ header = package.workbook.styles.add_style(
23
+ b: true,
24
+ bg_color: "1F4E78",
25
+ fg_color: "FFFFFF",
26
+ alignment: { horizontal: :center }
27
+ )
28
+ package.workbook.add_worksheet(name: "Orders") do |sheet|
29
+ sheet.add_row(["ID", "Customer"], style: header, types: %i[string string])
30
+ sheet.add_row([1, "Alice"], types: %i[string string])
31
+ end
32
+ bytes = package.to_stream.read
33
+ ```
34
+
35
+ ```ruby
36
+ # After (Phase 1: Oxcel::Compat::Caxlsx)
37
+ require "oxcel/compat/caxlsx"
38
+
39
+ package = Oxcel::Compat::Caxlsx::Package.new
40
+ package.use_shared_strings = true
41
+ header = package.workbook.styles.add_style(
42
+ b: true,
43
+ bg_color: "1F4E78",
44
+ fg_color: "FFFFFF",
45
+ alignment: { horizontal: :center }
46
+ )
47
+ package.workbook.add_worksheet(name: "Orders") do |sheet|
48
+ sheet.add_row(["ID", "Customer"], style: header, types: %i[string string])
49
+ sheet.add_row([1, "Alice"], types: %i[string string])
50
+ end
51
+ bytes = package.to_stream.read
52
+ ```
53
+
54
+ ### Verify Output Parity with `Oxcel.diff`
55
+
56
+ Run both writers in a test or shadow job and compare them cell-by-cell in O(1) memory:
57
+
58
+ ```ruby
59
+ result = Oxcel.diff("legacy_caxlsx.xlsx", "new_oxcel.xlsx", tolerance: 1e-9)
60
+ raise result.to_s if result.different?
61
+ ```
62
+
63
+ `Oxcel.diff` streams both files in lockstep, ignores trailing `nil` differences by default (`ignore_trailing_nils: true`), and reports exact A1 coordinates (`Orders!C42`) when anything diverges.
64
+
65
+ ---
66
+
67
+ ## Phase 2: Idiomatic `oxcel`
68
+
69
+ ### API Mapping
70
+
71
+ | `caxlsx` | `oxcel` (Native) | Notes |
72
+ |---|---|---|
73
+ | `Axlsx::Package.new` + `pkg.serialize(path)` | `Oxcel.write(path, constant_memory: true) { |wb| ... }` | Flat ~30 MB RSS even at 1M rows |
74
+ | `pkg.to_stream.read` | `Oxcel.to_bytes(constant_memory: true) { |wb| ... }` | Returns binary `String` directly |
75
+ | `wb.add_worksheet(name: "S1")` | `wb.add_sheet("S1")` | Yields `Oxcel::Sheet` |
76
+ | `wb.styles.add_style(b: true, fg_color: "FFFFFF", bg_color: "1F4E78", sz: 12, format_code: "#,##0")` | `wb.add_style(bold: true, font_color: "#FFFFFF", bg_color: "#1F4E78", font_size: 12, num_format: "#,##0")` | Leading `#` on hex colors |
77
+ | `alignment: { horizontal: :right, vertical: :center, wrap_text: true }` | `align: :right, valign: :center, text_wrap: true` | Flat keyword options |
78
+ | `border: { style: :thin, color: "000000", edges: [:bottom] }` | `border_bottom: :thin, border_color: "#000000"` | Per-edge or `border:` for all 4 sides |
79
+ | `sheet.add_row(vals, style: [s1, s2])` | `sheet.add_row(vals, styles: [s1, s2])` | `style:` = whole row, `styles:` = per column |
80
+ | `sheet.add_row(vals, types: %i[string string])` | Coerce values in Ruby (`val.to_s`) or use `Oxcel::Resource` | Preserves leading zeros (e.g. `"00123"`) |
81
+ | `sheet.merge_cells("A1:D1")` | `sheet.merge_range(0, 0, 0, 3, "Title", style: s)` | **0-indexed** `(first_row, first_col, last_row, last_col)` |
82
+ | `sheet.auto_filter = "A1:D10"` | `sheet.autofilter(0, 0, 9, 3)` | **0-indexed** |
83
+ | `sheet.sheet_view.pane { |p| p.state = :frozen; p.y_split = 1 }` | `sheet.freeze_panes(1, 0)` | Row/col count to freeze |
84
+ | `sheet.add_comment(ref: "A2", text: "Note")` | `sheet.add_note(1, 0, "Note")` | **0-indexed** |
85
+ | `sheet.add_data_validation("B2:B20", type: :list, formula1: '"A,B"')` | `sheet.add_dropdown(1, 1, 19, 1, %w[A B])` | **0-indexed** |
86
+ | Repeated `sheet.add_row` in a loop | `sheet.stream(relation.find_each) { |r| [...] }` or `Oxcel::Resource` | Batches 1,024 rows per Rust FFI call |
87
+
88
+ ### Declarative Export with `Oxcel::Resource`
89
+
90
+ For ActiveRecord / service exports, `Oxcel::Resource` eliminates boilerplate while keeping flat memory:
91
+
92
+ ```ruby
93
+ class StoreCodeExporter
94
+ include Oxcel::Resource
95
+
96
+ sheet_name "店舗コード"
97
+ constant_memory true
98
+ freeze_header true
99
+
100
+ column :name, header: "店舗名(必須)", width: 28
101
+ column :code, header: "店舗コード(英数字・ハイフン)", width: 28 do |store|
102
+ store.external_system_code.to_s
103
+ end
104
+ end
105
+
106
+ bytes = StoreCodeExporter.new(stores.find_each).to_bytes
107
+ ```
108
+
109
+ ---
110
+
111
+ ## Key Gotchas to Watch Out For
112
+
113
+ 1. **0-indexed coordinates**: Native `Oxcel::Sheet` methods (`write_cell`, `merge_range`, `autofilter`, `row_height`, `add_note`, `add_dropdown`) are **0-indexed**. (`Oxcel::Compat::Caxlsx` accepts A1 strings like `"A1:D1"`.)
114
+ 2. **`constant_memory: true` ordering rules**:
115
+ - Rows are flushed sequentially to a temp buffer as you advance to the next row.
116
+ - Set `row_height(row, h)` **before** writing the next row, and avoid going backward to earlier rows.
117
+ - Features that require random access across the sheet (`autofit`, `merge_range` on already-flushed rows, `add_note` on flushed rows) require `constant_memory: false` (pass `Oxcel::Compat::Caxlsx::Package.new(constant_memory: false)` or `wb.add_sheet("Report", constant_memory: false)`).
118
+ 3. **Hex colors**: Native `wb.add_style` expects `"#RRGGBB"` or `"#RGB"` (6-digit or 3-digit hex). `Oxcel::Compat::Caxlsx` automatically normalizes caxlsx's `"FFFFFF"` and 8-digit ARGB `"FF1F4E78"` to `"#FFFFFF"` / `"#1F4E78"`.
119
+ 4. **String preservation (`types: :string`)**: In `caxlsx`, `types: %i[string string]` prevents numeric-looking codes like `"00123"` from becoming numbers. In `oxcel`, Ruby `String` values are always written as Excel strings—just ensure the value is a `String` (`.to_s`) rather than an `Integer`.
120
+ 5. **Sorbet / Tapioca (`# typed: strict`)**: `oxcel` ships `rbi/oxcel.rbi` in the gem. Run `bin/tapioca gem oxcel` and Tapioca automatically imports full Sorbet signatures for `Oxcel`, `Oxcel::Resource`, `Oxcel.diff`, and `Oxcel::Compat::Caxlsx`.
@@ -0,0 +1,99 @@
1
+ # Migrating from `roo` to `oxcel`
2
+
3
+ `oxcel` replaces `roo`'s pure-Ruby XML parsing with Rust's `calamine` streaming reader (`XlsxCellReader`), delivering **~36x faster reads** and **~6x lower peak RSS (~30 MB flat)** across `.xlsx`, `.xlsm`, `.xlsb`, `.xls`, and `.ods`.
4
+
5
+ You can migrate in **two safe phases**:
6
+
7
+ 1. **Phase 1 (Drop-in adapter)**: Switch `Roo::Excelx` / `Roo::Spreadsheet` to `Oxcel::Compat::Roo` while keeping your 1-indexed row/cell code intact.
8
+ 2. **Phase 2 (Idiomatic Oxcel)**: Switch to `Oxcel.each_row` / `Oxcel.each_hash` for zero-overhead O(1) streaming and extensionless upload support (`Tempfile` / `StringIO` / bytes).
9
+
10
+ ---
11
+
12
+ ## Phase 1: Drop-in Adapter (`Oxcel::Compat::Roo`)
13
+
14
+ Require the opt-in adapter and replace `Roo::Excelx` / `Roo::Spreadsheet`:
15
+
16
+ ```ruby
17
+ # Before (roo)
18
+ require "roo"
19
+
20
+ sheet = Roo::Excelx.new(uploaded_file.path).sheet(0)
21
+ headers = sheet.row(1)
22
+ (2..sheet.last_row).each do |line_number|
23
+ process(sheet.row(line_number), line_number)
24
+ end
25
+ ```
26
+
27
+ ```ruby
28
+ # After (Phase 1: Oxcel::Compat::Roo)
29
+ require "oxcel/compat/roo"
30
+
31
+ sheet = Oxcel::Compat::Roo::Excelx.new(uploaded_file.path).sheet(0)
32
+ headers = sheet.row(1)
33
+ (2..(sheet.last_row || 0)).each do |line_number|
34
+ process(sheet.row(line_number), line_number)
35
+ end
36
+ ```
37
+
38
+ Supported `Oxcel::Compat::Roo` APIs:
39
+ - `Oxcel::Compat::Roo::Excelx.new(path_or_io, extension: nil)`
40
+ - `Oxcel::Compat::Roo::Spreadsheet.open(path_or_io, extension: nil)`
41
+ - `sheets`, `default_sheet`, `default_sheet=`, `sheet(index_or_name)`, `close`
42
+ - 1-indexed `first_row`, `last_row`, `first_column`, `last_column`, `row(n)`, `cell(row, col_or_letter)`
43
+ - O(1) streaming `each_row_streaming(offset: 0, max_rows: nil)` (yields `Cell` objects with `.value`, `.coordinate`, `.empty?`)
44
+ - `parse(headers: true)` (matches Roo 4.0: includes header row at index 0) and `parse(col_key: "Header", clean: true)` (excludes header row)
45
+
46
+ ---
47
+
48
+ ## Phase 2: Idiomatic `oxcel`
49
+
50
+ ### API Mapping
51
+
52
+ | `roo` | `oxcel` (Native) | Notes |
53
+ |---|---|---|
54
+ | `Roo::Excelx.new(path)` | `Oxcel.open(path)` / `Oxcel::Reader.new(path)` | Also accepts `IO`, `StringIO`, `Tempfile`, `Pathname` |
55
+ | `Roo::Spreadsheet.open(io, extension: :xlsx)` | `Oxcel.open(io, format: :xlsx)` or `Oxcel.open_bytes(bytes)` | Auto-detects format by magic bytes even without extension |
56
+ | `xlsx.sheets` | `reader.sheet_names` | Returns `Array<String>` |
57
+ | `sheet.each_row_streaming(offset: 1) { |cells| cells.map(&:value) }` | `Oxcel.each_row(path, coerce_integers: true)` | Yields raw Ruby values directly (no per-cell wrapper objects); supports lazy `.first(N)` |
58
+ | `sheet.parse(headers: true).drop(1)` | `Oxcel.each_hash(path, coerce_integers: true)` | Automatically uses first row as header and skips it in yielded hashes |
59
+ | `sheet.parse(clean: true)` | `Oxcel.each_hash(path, symbolize_keys: true)` | Stream one hash at a time in O(1) memory |
60
+ | `sheet.last_row` / `last_column` | `reader.dimensions(sheet)` | Returns `[rows, cols]` or `nil` |
61
+ | `rescue Zip::Error, Roo::Error` | `rescue Oxcel::FileError, Oxcel::Error` | Clean exception hierarchy (`Oxcel::Error < StandardError`) |
62
+
63
+ ### Streaming Example (Replacing `sheet.row(n)` Loops)
64
+
65
+ Instead of loading the entire sheet into RAM with `sheet.row(2..last_row)`, stream row-by-row with `each_row`:
66
+
67
+ ```ruby
68
+ Oxcel.open(uploaded_file.path) do |reader|
69
+ enum = reader.each_row(0, coerce_integers: true)
70
+ header = enum.first
71
+ raise InvalidFileError, "Invalid headers" unless header == REQUIRED_HEADERS
72
+
73
+ reader.each_row(0, coerce_integers: true).with_index(1) do |row, line_number|
74
+ next if line_number == 1
75
+ raise InvalidFileError, "Too many rows" if line_number - 1 > MAX_ROW_COUNT
76
+
77
+ process(row, line_number)
78
+ end
79
+ end
80
+ ```
81
+
82
+ ---
83
+
84
+ ## Key Gotchas to Watch Out For
85
+
86
+ 1. **0-indexed vs 1-indexed**:
87
+ - Native `Oxcel` (`dimensions`, `merged_regions`, `formulas`) is **0-indexed**; `each_row` yields plain Ruby arrays.
88
+ - `Oxcel::Compat::Roo` preserves Roo's **1-indexed** `row(1)`, `cell(1, 1)` / `cell(1, "A")`, `first_row`, `last_row`.
89
+ 2. **Integer coercion**:
90
+ - Excel stores all numbers as IEEE 754 `f64`. Pass `coerce_integers: true` to `Oxcel.each_row` / `Oxcel.each_hash` / `Oxcel.read` so whole numbers like `42.0` come back as Ruby `Integer` (`42`), matching Roo's integer behavior. (`Oxcel::Compat::Roo` enables `coerce_integers: true` by default.)
91
+ 3. **Dates vs Times**:
92
+ - Pure Excel dates (no fractional time component) return Ruby `Date`.
93
+ - Excel datetimes (with fractional time component) return UTC `Time`.
94
+ 4. **Error handling**:
95
+ - Replace `rescue Zip::Error, Roo::Error` with `rescue Oxcel::FileError, Oxcel::Error` (all Oxcel runtime/format errors inherit from `Oxcel::Error < StandardError`).
96
+ 5. **Uploaded files without extensions**:
97
+ - Rails `ActionDispatch::Http::UploadedFile` and `Tempfile` often lack a `.xlsx` suffix. `Oxcel` inspects magic bytes automatically (or accepts `format: :xlsx` explicitly), so you never need Roo's `extension: :xlsx` workaround.
98
+ 6. **Sorbet / Tapioca (`# typed: strict`)**:
99
+ - `oxcel` bundles `rbi/oxcel.rbi`. Run `bin/tapioca gem oxcel` and Sorbet immediately gets strict signatures for `Oxcel`, `Oxcel::Reader`, and `Oxcel::Compat::Roo`.
Binary file
Binary file
Binary file
data/lib/oxcel/a1.rb ADDED
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Oxcel
4
+ # Excel A1-notation coordinate helpers (0-indexed internally).
5
+ #
6
+ # Oxcel::A1.col_to_letters(0) # => "A"
7
+ # Oxcel::A1.col_to_letters(27) # => "AB"
8
+ # Oxcel::A1.letters_to_col("AB") # => 27
9
+ # Oxcel::A1.format_cell(0, 0) # => "A1"
10
+ # Oxcel::A1.parse_cell("B3") # => [2, 1]
11
+ # Oxcel::A1.parse_range("A1:D10") # => [0, 0, 9, 3]
12
+ module A1
13
+ module_function
14
+
15
+ def col_to_letters(index)
16
+ raise ArgumentError, "column index must be >= 0" if index < 0
17
+
18
+ letters = +""
19
+ n = index + 1
20
+ while n > 0
21
+ n, rem = (n - 1).divmod(26)
22
+ letters.prepend((65 + rem).chr)
23
+ end
24
+ letters
25
+ end
26
+
27
+ def letters_to_col(letters)
28
+ s = letters.to_s.strip.upcase
29
+ raise ArgumentError, "invalid column letter: #{letters.inspect}" unless s.match?(/\A[A-Z]+\z/)
30
+
31
+ idx = 0
32
+ s.each_byte { |b| idx = idx * 26 + (b - 64) }
33
+ idx - 1
34
+ end
35
+
36
+ def format_cell(row, col)
37
+ raise ArgumentError, "row must be >= 0" if row < 0
38
+
39
+ "#{col_to_letters(col)}#{row + 1}"
40
+ end
41
+
42
+ def parse_cell(ref)
43
+ m = /\A\$?([A-Za-z]+)\$?(\d+)\z/.match(ref.to_s.strip)
44
+ raise ArgumentError, "invalid A1 cell reference: #{ref.inspect}" unless m
45
+
46
+ row = m[2].to_i - 1
47
+ raise ArgumentError, "row must be >= 1 in #{ref.inspect}" if row < 0
48
+
49
+ [row, letters_to_col(m[1])]
50
+ end
51
+
52
+ def parse_range(range_str)
53
+ parts = range_str.to_s.split(":")
54
+ if parts.size == 1
55
+ r, c = parse_cell(parts[0])
56
+ [r, c, r, c]
57
+ elsif parts.size == 2
58
+ r1, c1 = parse_cell(parts[0])
59
+ r2, c2 = parse_cell(parts[1])
60
+ [r1, c1, r2, c2]
61
+ else
62
+ raise ArgumentError, "invalid A1 range: #{range_str.inspect}"
63
+ end
64
+ end
65
+ end
66
+ end