From f32fefddcf6961da5bc101090dfac4154542e006 Mon Sep 17 00:00:00 2001 From: nihilist-narwhal <240798405+nihilist-narwhal@users.noreply.github.com> Date: Mon, 2 Nov 2026 07:34:22 -0600 Subject: [PATCH] Tables never hold merged cells, which Excel removes the table for on open A table with a merged cell in it opened in Excel with the repair prompt, and Excel removed the table and its AutoFilter ("Removed Feature: Table from /xl/tables/table1.xml"). GridCraft let merged cells into a table four ways; each now does what Excel does: - Merge Cells, Merge & Center and Merge Across refuse a range that touches a table ("You can't merge cells in a table."). Unmerging is still allowed, so a file that has one can be fixed. - Insert Table / Format as Table and Resize Table unmerge the merged cells the table covers (observed: Excel creates the table and A2:B2 is no longer merged). - Paste brings merged areas along, except into a table, where the cells arrive unmerged. The command-sequence fuzzer checks the invariant (it found the paste case, seed 230). --- crates/engine/src/cmd/edit/paste_special.rs | 5 ++ crates/engine/src/cmd/extra/data.rs | 2 + crates/engine/src/cmd/format.rs | 5 ++ crates/engine/src/cmd/insert.rs | 7 +++ crates/engine/src/tests.rs | 60 +++++++++++++++++++ .../engine/tests/it/command_sequence_fuzz.rs | 6 +- crates/engine/tests/it/sheet_copy_spill.rs | 2 +- 7 files changed, 85 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/edit/paste_special.rs b/crates/engine/src/cmd/edit/paste_special.rs index c90dd9ec80..0c2f17a3dc 100644 --- a/crates/engine/src/cmd/edit/paste_special.rs +++ b/crates/engine/src/cmd/edit/paste_special.rs @@ -361,6 +361,11 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { if let (Some(a), Some(b)) = (m.start.offset(dr, dc), m.end.offset(dr, dc)) { let nm = RangeRef::new(a, b); let sh = cx.sheet_mut(dest_sheet)?; + // A table can't hold merged cells (Excel removes the table on open): the + // cells are pasted there unmerged. + if sh.tables.iter().any(|t| t.range.intersects(&nm)) { + continue; + } sh.merges.retain(|x| !x.intersects(&nm)); sh.merges.push(nm); } diff --git a/crates/engine/src/cmd/extra/data.rs b/crates/engine/src/cmd/extra/data.rs index 5af7df0a86..9940ffc459 100644 --- a/crates/engine/src/cmd/extra/data.rs +++ b/crates/engine/src/cmd/extra/data.rs @@ -37,6 +37,8 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result { } t.columns = cols; t.range = r; + // A table can't hold merged cells: those it now covers are unmerged, as by Insert Table. + sheet.merges.retain(|m| !m.intersects(&r)); cx.structural = true; Ok(Json::Null) }) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index 90213a5e1c..d512b7a0cb 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -637,6 +637,11 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result { let ranges = target_ranges(s, p)?; let how = if how == "center" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| ranges.iter().all(|r| sh.merges.contains(r))) { "unmerge" } else { how }; + // Excel has no merged cells in a table (a file with one loses the table when Excel opens it): + // merging there is refused, unmerging is still allowed. + if how != "unmerge" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| ranges.iter().any(|r| t.range.intersects(r)))) { + return Err(EngineError::Other("You can't merge cells in a table.".into())); + } edit(s, |cx| { let mut touched = Vec::new(); // Areas whose merging changes: a merged cell blocks a dynamic array's spill. diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 4bd564db37..f88c6040fa 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -334,6 +334,13 @@ fn insert_table(s: &mut Session, p: &Json) -> Result { RangeRef::new(r.start, CellRef::new((r.end.row + 1).min(MAX_ROWS - 1), r.end.col)) }; let sh = cx.sheet_mut(sheet)?; + // As in Excel, the table unmerges the merged cells it covers: a table can't hold them. + let merged = sh.merges.len(); + sh.merges.retain(|m| !m.intersects(&r)); + if sh.merges.len() != merged { + cx.structural = true; + } + let sh = cx.sheet_mut(sheet)?; let mut names: Vec = Vec::new(); // Lower-case names taken, and the next suffix for each header, so that thousands of equal // headers don't take cubic time. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f000eb9fe1..5cc071d5a3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6728,3 +6728,63 @@ fn history_charges_the_storage_of_empty_comment_replies() { // 500 replies of no text are still 500 elements. assert!(crate::sheet_text_bytes(&sheet) >= 500 * std::mem::size_of::<(String, String)>()); } + +#[test] +fn tables_never_hold_merged_cells() { + // Excel removes a table that contains a merged cell when it opens the file. Merging in a + // table is refused; making or resizing a table over merged cells unmerges them; pasting into + // a table skips the merges. + let base = || { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1:D4", "values": [["A", "B", "C", "D"], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]})) + .unwrap(); + s + }; + let merges = |s: &Session| s.doc().unwrap().wb.active().unwrap().merges.clone(); + + let mut s = base(); + s.execute("insert.table", json!({"range": "A1:C4"})).unwrap(); + for id in ["home.mergeCells", "home.mergeCenter", "home.mergeAcross"] { + for range in ["A2:B2", "A1:B1", "C3:D3"] { + let e = s.execute(id, json!({"range": range})).unwrap_err().to_string(); + assert!(e.contains("can't merge cells in a table"), "{id} {range}: {e}"); + } + } + assert!(merges(&s).is_empty()); + s.execute("home.mergeCells", json!({"range": "E2:F2"})).unwrap(); + assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("E2:F2").unwrap()]); + + // A table over merged cells unmerges them; undo brings them back. + let mut s = base(); + s.execute("home.mergeCells", json!({"range": "A2:B2"})).unwrap(); + s.execute("home.mergeCells", json!({"range": "C3:D4"})).unwrap(); + s.execute("home.mergeCells", json!({"range": "F1:G1"})).unwrap(); + s.execute("insert.table", json!({"range": "A1:C4"})).unwrap(); + assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("F1:G1").unwrap()]); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(merges(&s).len(), 3); + s.execute("edit.redo", json!({})).unwrap(); + + // Resizing a table over merged cells unmerges them too. + let mut s = base(); + s.execute("insert.table", json!({"range": "A1:B4", "name": "T"})).unwrap(); + s.execute("home.mergeCells", json!({"range": "C2:D2"})).unwrap(); + s.execute("table.resize", json!({"table": "T", "range": "A1:C4"})).unwrap(); + assert!(merges(&s).is_empty()); + + // Merged cells pasted into a table arrive unmerged; elsewhere they stay merged. + s.execute("home.mergeCells", json!({"range": "E2:F3"})).unwrap(); + s.execute("edit.copy", json!({"range": "E2:F3"})).unwrap(); + s.execute("edit.paste", json!({"at": "A2"})).unwrap(); + s.execute("edit.paste", json!({"at": "H2"})).unwrap(); + assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("E2:F3").unwrap(), gridcraft_core::RangeRef::parse("H2:I3").unwrap()]); + + // The saved file has no merge inside the table. + let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap(); + let bytes = crate::io::base64_decode(saved["base64"].as_str().unwrap()).unwrap(); + let (back, _) = crate::io::open_bytes("t.xlsx", &bytes).unwrap(); + let sh = back.active().unwrap(); + assert_eq!(sh.tables.len(), 1); + assert_eq!(sh.tables[0].range, gridcraft_core::RangeRef::parse("A1:C4").unwrap()); + assert!(sh.merges.iter().all(|m| sh.tables.iter().all(|t| !t.range.intersects(m)))); +} diff --git a/crates/engine/tests/it/command_sequence_fuzz.rs b/crates/engine/tests/it/command_sequence_fuzz.rs index 89b3e91865..949f637539 100644 --- a/crates/engine/tests/it/command_sequence_fuzz.rs +++ b/crates/engine/tests/it/command_sequence_fuzz.rs @@ -12,7 +12,7 @@ //! and saving, reloading or recalculating never panics either; //! - a non-undoable command never changes cell content (it would be lost to undo); //! - the structure stays valid: active sheet in range, sheet and table names valid and unique, -//! merges and tables on the sheet and not overlapping, legacy arrays anchored at their +//! merges and tables on the sheet and not overlapping (nor a merge inside a table), legacy arrays anchored at their //! top-left cell, the selection on the sheet; //! - a full recalculation from scratch gives the values the incremental recalculation left //! (catches stale dependency graphs); @@ -408,6 +408,10 @@ fn structure_problem(wb: &Workbook, sel: &gridcraft_engine::Selection) -> Option if let Some(o) = sh.tables.iter().skip(k + 1).find(|o| overlaps(&t.range, &o.range)) { return Some(format!("{}: tables `{}` ({}) and `{}` ({}) overlap", sh.name, t.name, t.range, o.name, o.range)); } + // Excel removes a table that holds a merged cell when it opens the file. + if let Some(m) = sh.merges.iter().find(|m| overlaps(&t.range, m)) { + return Some(format!("{}: table `{}` ({}) holds merged cells {m}", sh.name, t.name, t.range)); + } } } if sel.ranges.is_empty() || !sel.active.is_valid() || sel.ranges.iter().any(|r| !r.start.is_valid() || !r.end.is_valid()) { diff --git a/crates/engine/tests/it/sheet_copy_spill.rs b/crates/engine/tests/it/sheet_copy_spill.rs index aed68baf97..481f9889ee 100644 --- a/crates/engine/tests/it/sheet_copy_spill.rs +++ b/crates/engine/tests/it/sheet_copy_spill.rs @@ -17,7 +17,7 @@ fn value(s: &Session, sheet: &str, cell: &str) -> Value { fn copied_sheet_keeps_spill_values_through_full_recalc() { let mut s = Session::new(); run(&mut s, "file.new", json!({"sample": "grades"})); - run(&mut s, "home.mergeCells", json!({"range": "F:H"})); + run(&mut s, "home.mergeCells", json!({"range": "F15:H20"})); run(&mut s, "cell.set", json!({"cell": "J54", "input": "=SEQUENCE(5)*C6"})); run(&mut s, "selection.set", json!({"range": "15:15"})); run(&mut s, "sheet.move", json!({"copy": true, "sheet": 0, "to": 1}));