excelerate 0.15.0

Read, write and recalculate spreadsheets: xlsx, xls, ods, csv, html, and a 518-function formula engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Editing the grid: rows, columns and cells inserted and removed, blocks
//! copied, moved, sorted and filled, sheets moved and removed. Every one of
//! these rewrites formulas across the workbook, so each drops the dependency
//! index when it succeeds.

use super::convert::{array, col_at, row_at};
use super::{Book, js};
use crate::coordinate::{CellRef, Col, Range, Row};
use crate::edit::{Axis, CopyOrigin, SortBy, SortKey, SortOptions};
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
impl Book {
    /// Inserts `count` rows above row `at`, moving everything below down.
    /// `copyOrigin` - `"before"` (the row above), `"after"` (the row below)
    /// or `"none"` - says whose formatting the new rows take. Left out, it is
    /// `"before"`, as in Excel.
    ///
    /// Formulas across the whole workbook follow the cells they read, and so
    /// do merges, links, validations, tables and drawings. `at` is the number
    /// a user sees.
    #[wasm_bindgen(js_name = insertRows)]
    #[expect(
        clippy::needless_pass_by_value,
        reason = "an optional string crosses the wasm boundary owned"
    )]
    pub fn insert_rows(
        &mut self,
        sheet: usize,
        at: u32,
        count: u32,
        #[wasm_bindgen(
            js_name = "copyOrigin",
            unchecked_optional_param_type = "\"before\" | \"after\" | \"none\""
        )]
        copy_origin: Option<String>,
    ) -> Result<(), JsError> {
        let row = Row::from_one_based(u64::from(at)).map_err(js)?;
        let origin = copy_origin_of(copy_origin.as_deref())?;
        let done = crate::edit::insert_rows_with(&mut self.workbook, sheet, row, count, origin);
        self.edited(done)
    }

    /// Removes `count` rows from row `at` down. A formula that read a removed
    /// cell reads `#REF!` afterwards.
    #[wasm_bindgen(js_name = removeRows)]
    pub fn remove_rows(&mut self, sheet: usize, at: u32, count: u32) -> Result<(), JsError> {
        let row = Row::from_one_based(u64::from(at)).map_err(js)?;
        let done = crate::edit::remove_rows(&mut self.workbook, sheet, row, count);
        self.edited(done)
    }

    /// Inserts `count` columns to the left of column `at`, 1-based.
    /// `copyOrigin` works as in `insertRows`, with left and right.
    #[wasm_bindgen(js_name = insertColumns)]
    #[expect(
        clippy::needless_pass_by_value,
        reason = "an optional string crosses the wasm boundary owned"
    )]
    pub fn insert_columns(
        &mut self,
        sheet: usize,
        at: u32,
        count: u32,
        #[wasm_bindgen(
            js_name = "copyOrigin",
            unchecked_optional_param_type = "\"before\" | \"after\" | \"none\""
        )]
        copy_origin: Option<String>,
    ) -> Result<(), JsError> {
        let col = Col::from_one_based(u64::from(at)).map_err(js)?;
        let origin = copy_origin_of(copy_origin.as_deref())?;
        let done = crate::edit::insert_columns_with(&mut self.workbook, sheet, col, count, origin);
        self.edited(done)
    }

    /// Removes `count` columns from column `at`, 1-based.
    #[wasm_bindgen(js_name = removeColumns)]
    pub fn remove_columns(&mut self, sheet: usize, at: u32, count: u32) -> Result<(), JsError> {
        let col = Col::from_one_based(u64::from(at)).map_err(js)?;
        let done = crate::edit::remove_columns(&mut self.workbook, sheet, col, count);
        self.edited(done)
    }

    /// Inserts rows at many places in one pass: `places` is `[at, count]`
    /// pairs, numbered as the sheet is before the call, in any order.
    /// `book.insertRowsMany(0, [[5, 1], [9, 1]])` puts a row above each of
    /// rows 5 and 9 - the old row 9, now row 10. Each new block takes its
    /// formatting from its own neighbour, as `copyOrigin` says.
    ///
    /// The result is that of the single inserts made from the bottom up, but
    /// the workbook is walked once rather than once per place: four thousand
    /// subtotal rows into forty thousand take milliseconds, not a minute.
    #[wasm_bindgen(js_name = insertRowsMany)]
    #[expect(
        clippy::needless_pass_by_value,
        reason = "an optional string crosses the wasm boundary owned"
    )]
    pub fn insert_rows_many(
        &mut self,
        sheet: usize,
        #[wasm_bindgen(unchecked_param_type = "[number, number][]")] places: &JsValue,
        #[wasm_bindgen(
            js_name = "copyOrigin",
            unchecked_optional_param_type = "\"before\" | \"after\" | \"none\""
        )]
        copy_origin: Option<String>,
    ) -> Result<(), JsError> {
        let at = places_of(places, row_at)?;
        let origin = copy_origin_of(copy_origin.as_deref())?;
        let done = crate::edit::insert_rows_many(&mut self.workbook, sheet, &at, origin);
        self.edited(done)
    }

    /// Removes rows at many places in one pass: `[at, count]` pairs, numbered
    /// as the sheet is before the call. Blocks that overlap are merged.
    #[wasm_bindgen(js_name = removeRowsMany)]
    pub fn remove_rows_many(
        &mut self,
        sheet: usize,
        #[wasm_bindgen(unchecked_param_type = "[number, number][]")] places: &JsValue,
    ) -> Result<(), JsError> {
        let spans = places_of(places, row_at)?;
        let done = crate::edit::remove_rows_many(&mut self.workbook, sheet, &spans);
        self.edited(done)
    }

    /// `insertRowsMany` for columns.
    #[wasm_bindgen(js_name = insertColumnsMany)]
    #[expect(
        clippy::needless_pass_by_value,
        reason = "an optional string crosses the wasm boundary owned"
    )]
    pub fn insert_columns_many(
        &mut self,
        sheet: usize,
        #[wasm_bindgen(unchecked_param_type = "[number, number][]")] places: &JsValue,
        #[wasm_bindgen(
            js_name = "copyOrigin",
            unchecked_optional_param_type = "\"before\" | \"after\" | \"none\""
        )]
        copy_origin: Option<String>,
    ) -> Result<(), JsError> {
        let at = places_of(places, col_at)?;
        let origin = copy_origin_of(copy_origin.as_deref())?;
        let done = crate::edit::insert_columns_many(&mut self.workbook, sheet, &at, origin);
        self.edited(done)
    }

    /// `removeRowsMany` for columns.
    #[wasm_bindgen(js_name = removeColumnsMany)]
    pub fn remove_columns_many(
        &mut self,
        sheet: usize,
        #[wasm_bindgen(unchecked_param_type = "[number, number][]")] places: &JsValue,
    ) -> Result<(), JsError> {
        let spans = places_of(places, col_at)?;
        let done = crate::edit::remove_columns_many(&mut self.workbook, sheet, &spans);
        self.edited(done)
    }

    /// Inserts blank cells over a range, pushing what was there `"down"` or
    /// `"right"` - Excel's "Insert Cells", which moves part of a row rather
    /// than the whole of it. `copyOrigin` works as in `insertRows`.
    #[wasm_bindgen(js_name = insertCells)]
    #[expect(
        clippy::needless_pass_by_value,
        reason = "an optional string crosses the wasm boundary owned"
    )]
    pub fn insert_cells(
        &mut self,
        sheet: usize,
        range: &str,
        #[wasm_bindgen(unchecked_param_type = "\"down\" | \"right\"")] shift: &str,
        #[wasm_bindgen(
            js_name = "copyOrigin",
            unchecked_optional_param_type = "\"before\" | \"after\" | \"none\""
        )]
        copy_origin: Option<String>,
    ) -> Result<(), JsError> {
        let area = Range::parse(range).map_err(js)?;
        let origin = copy_origin_of(copy_origin.as_deref())?;
        let done = crate::edit::insert_cells_with(
            &mut self.workbook,
            sheet,
            area,
            axis_of(shift)?,
            origin,
        );
        self.edited(done)
    }

    /// Removes the cells of a range, pulling the rest back over the hole from
    /// below (`"up"`) or from the right (`"left"`).
    #[wasm_bindgen(js_name = removeCells)]
    pub fn remove_cells(
        &mut self,
        sheet: usize,
        range: &str,
        #[wasm_bindgen(unchecked_param_type = "\"up\" | \"left\"")] shift: &str,
    ) -> Result<(), JsError> {
        let area = Range::parse(range).map_err(js)?;
        let done = crate::edit::remove_cells(&mut self.workbook, sheet, area, axis_of(shift)?);
        self.edited(done)
    }

    /// Copies a rectangle of cells so its top left corner lands on `to`,
    /// rewriting the formulas as Excel rewrites a copied formula: `=A1` one
    /// row down reads `=A2`, `$A$1` stays put.
    ///
    /// `toSheet` defaults to the sheet copied from. A cell the source leaves
    /// empty empties the target, the way pasting a block does.
    #[wasm_bindgen(js_name = copyRange)]
    pub fn copy_range(
        &mut self,
        sheet: usize,
        range: &str,
        to: &str,
        to_sheet: Option<usize>,
    ) -> Result<(), JsError> {
        let (area, at) = (
            Range::parse(range).map_err(js)?,
            CellRef::parse(to).map_err(js)?,
        );
        let done = crate::edit::copy_range(
            &mut self.workbook,
            sheet,
            area,
            to_sheet.unwrap_or(sheet),
            at,
        );
        self.edited(done)
    }

    /// Moves a rectangle of cells, leaving the source empty.
    ///
    /// A moved formula keeps reading the cells it read; the formulas elsewhere
    /// that read *these* cells follow them instead, as they do when Excel cuts
    /// and pastes.
    #[wasm_bindgen(js_name = moveRange)]
    pub fn move_range(
        &mut self,
        sheet: usize,
        range: &str,
        to: &str,
        to_sheet: Option<usize>,
    ) -> Result<(), JsError> {
        let (area, at) = (
            Range::parse(range).map_err(js)?,
            CellRef::parse(to).map_err(js)?,
        );
        let done = crate::edit::move_range(
            &mut self.workbook,
            sheet,
            area,
            to_sheet.unwrap_or(sheet),
            at,
        );
        self.edited(done)
    }

    /// Sorts the rows of a range, or its columns. A key is a column number of
    /// the sheet, 1-based (a row number when sorting columns), or the text of
    /// a header when `options.header` says the first line is one; a minus
    /// sorts it largest first: `[2, -4]`, `["Region", "-Amount"]`. The first
    /// key decides first.
    ///
    /// ```js
    /// book.sortRange(0, "A1:D100", ["Region", "-Amount"], { header: true });
    /// ```
    #[wasm_bindgen(js_name = sortRange)]
    pub fn sort_range(
        &mut self,
        sheet: usize,
        range: &str,
        #[wasm_bindgen(unchecked_param_type = "SortKeys")] keys: &JsValue,
        #[wasm_bindgen(unchecked_optional_param_type = "SortRangeOptions")] options: &JsValue,
    ) -> Result<(), JsError> {
        let area = Range::parse(range).map_err(js)?;
        let flag = |name: &str| super::convert::field(options, name).is_some_and(|v| v.is_truthy());
        let options = SortOptions {
            header: flag("header"),
            orientation: if flag("byColumns") {
                Axis::Columns
            } else {
                Axis::Rows
            },
        };
        let keys = sort_keys_of(keys)?;
        let done = crate::edit::sort_range_with(&mut self.workbook, sheet, area, &keys, options);
        self.edited(done)
    }

    /// Sorts the data rows of a table, found by name anywhere in the book;
    /// its header and totals rows stay put. Keys name its columns, as in
    /// `sortRange`: `book.sortTable("Sales", ["-Amount"])`.
    #[wasm_bindgen(js_name = sortTable)]
    pub fn sort_table(
        &mut self,
        name: &str,
        #[wasm_bindgen(unchecked_param_type = "SortKeys")] keys: &JsValue,
    ) -> Result<(), JsError> {
        let keys = sort_keys_of(keys)?;
        let done = crate::edit::sort_table(&mut self.workbook, name, &keys);
        self.edited(done)
    }

    /// Continues what the first cells of a range start, as dragging the fill
    /// handle does: `1, 2` goes on `3, 4`, `Кв1` to `Кв2`, `Jan` to `Feb`, a
    /// date by a day; anything else repeats. `"down"` fills each column,
    /// `"right"` each row; `"up"` and `"left"` run the series back from the
    /// last cells.
    #[wasm_bindgen(js_name = fillSeries)]
    pub fn fill_series(
        &mut self,
        sheet: usize,
        range: &str,
        #[wasm_bindgen(unchecked_param_type = "\"down\" | \"right\" | \"up\" | \"left\"")]
        direction: &str,
    ) -> Result<(), JsError> {
        let area = Range::parse(range).map_err(js)?;
        let fill = match direction {
            "down" | "right" => crate::edit::fill_series,
            "up" | "left" => crate::edit::fill_series_back,
            _ => {
                return Err(JsError::new(
                    r#"a fill goes "down", "right", "up" or "left""#,
                ));
            }
        };
        let done = fill(&mut self.workbook, sheet, area, axis_of(direction)?);
        self.edited(done)
    }

    /// Copies the first row of a range into the rows below it, as Ctrl+D.
    #[wasm_bindgen(js_name = fillDown)]
    pub fn fill_down(&mut self, sheet: usize, range: &str) -> Result<(), JsError> {
        let area = Range::parse(range).map_err(js)?;
        let done = crate::edit::fill(&mut self.workbook, sheet, area, Axis::Rows);
        self.edited(done)
    }

    /// Copies the first column of a range into the columns to its right, as
    /// Ctrl+R.
    #[wasm_bindgen(js_name = fillRight)]
    pub fn fill_right(&mut self, sheet: usize, range: &str) -> Result<(), JsError> {
        let area = Range::parse(range).map_err(js)?;
        let done = crate::edit::fill(&mut self.workbook, sheet, area, Axis::Columns);
        self.edited(done)
    }

    /// Moves a sheet along the tab bar. Formulas are untouched - a sheet is
    /// named, not numbered - but every index moves, this one included, so read
    /// `sheetIndex` again afterwards.
    #[wasm_bindgen(js_name = moveSheet)]
    pub fn move_sheet(&mut self, from: usize, to: usize) -> Result<(), JsError> {
        crate::edit::move_sheet(&mut self.workbook, from, to).map_err(js)
    }

    /// Removes a sheet. References to it from anywhere in the workbook become
    /// `#REF!`, the way Excel writes them, and the sheets after it shift down
    /// by one index.
    #[wasm_bindgen(js_name = removeSheet)]
    pub fn remove_sheet(&mut self, sheet: usize) -> Result<(), JsError> {
        let done = crate::edit::remove_sheet(&mut self.workbook, sheet);
        self.edited(done)
    }
}

impl Book {
    /// The end of every edit: its error for JS, or the dependency index
    /// dropped, since every address in it may have moved.
    fn edited(&mut self, done: crate::error::Result<()>) -> Result<(), JsError> {
        done.map_err(js)?;
        self.forget_dependencies();
        Ok(())
    }
}

/// Which way a shift or a fill runs.
fn axis_of(direction: &str) -> Result<Axis, JsError> {
    match direction {
        "down" | "up" => Ok(Axis::Rows),
        "right" | "left" => Ok(Axis::Columns),
        _ => Err(JsError::new(
            r#"a shift is "down", "up", "right" or "left""#,
        )),
    }
}

/// Reads the `[at, count]` pairs of the batch edits, `at` 1-based.
fn places_of<T>(
    places: &JsValue,
    line: fn(u32) -> Result<T, JsError>,
) -> Result<Vec<(T, u32)>, JsError> {
    let number = |v: JsValue| {
        v.as_f64()
            .filter(|n| n.fract() == 0.0 && (0.0..=f64::from(u32::MAX)).contains(n))
            .ok_or_else(|| JsError::new("a place is [at, count], two whole numbers"))
    };
    array(places, "places")?
        .iter()
        .map(|pair| {
            let pair = array(&pair, "a place")?;
            #[expect(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss,
                reason = "checked whole and in range just above"
            )]
            let (at, count) = (number(pair.get(0))? as u32, number(pair.get(1))? as u32);
            Ok((line(at)?, count))
        })
        .collect()
}

/// Reads the `copyOrigin` argument of the inserts.
fn copy_origin_of(name: Option<&str>) -> Result<CopyOrigin, JsError> {
    match name {
        Some("none") => Ok(CopyOrigin::Blank),
        None | Some("before") => Ok(CopyOrigin::Before),
        Some("after") => Ok(CopyOrigin::After),
        Some(other) => Err(JsError::new(&format!(
            "copyOrigin must be \"before\", \"after\" or \"none\", not {other:?}"
        ))),
    }
}

/// Reads the keys of `sortRange`: a number is a 1-based line of the sheet, a
/// string a header; a minus in front sorts largest first.
fn sort_keys_of(keys: &JsValue) -> Result<Vec<SortKey>, JsError> {
    array(keys, "sort keys")?
        .iter()
        .map(|key| {
            if let Some(n) = key.as_f64() {
                #[expect(
                    clippy::cast_possible_truncation,
                    clippy::cast_sign_loss,
                    reason = "a line number of the sheet, saturated if it is not one"
                )]
                let line = (n.abs() as u32)
                    .checked_sub(1)
                    .ok_or_else(|| JsError::new("a sort key counts from 1"))?;
                return Ok(SortKey {
                    by: SortBy::Line(line),
                    descending: n < 0.0,
                });
            }
            let text = key
                .as_string()
                .ok_or_else(|| JsError::new("a sort key is a number or a header"))?;
            Ok(match text.strip_prefix('-') {
                Some(name) => SortKey::header(name).descending(),
                None => SortKey::header(text),
            })
        })
        .collect()
}