Merge pull request #2331 from nihilist-narwhal/fix/no-merged-cells-in-tables

Tables never hold merged cells, which Excel removes the table for on open
This commit is contained in:
FredApps
2026-11-26 22:06:09 +01:00
committed by GitHub
6 changed files with 85 additions and 2 deletions
@@ -421,6 +421,11 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
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);
}
+5
View File
@@ -642,6 +642,11 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result<Json> {
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.
+7
View File
@@ -74,6 +74,13 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
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<String> = Vec::new();
// Lower-case names taken, and the next suffix for each header, so that thousands of equal
// headers don't take cubic time.
+62
View File
@@ -8172,6 +8172,68 @@ fn history_charges_the_storage_of_empty_comment_replies() {
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 is refused, as in Excel; the merge stays.
let mut s = base();
s.execute("insert.table", json!({"range": "A1:B4", "name": "T"})).unwrap();
s.execute("home.mergeCells", json!({"range": "C2:D2"})).unwrap();
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:C4"})).unwrap_err().to_string();
assert!(e.contains("can't overlap merged cells"), "{e}");
s.execute("home.unmergeCells", json!({"range": "C2:D2"})).unwrap();
s.execute("table.resize", json!({"table": "T", "range": "A1:C4"})).unwrap();
// 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))));
}
#[test]
fn hyperlink_function_makes_a_cell_link() {
let mut s = s();
@@ -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);
@@ -442,6 +442,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()) {
+1 -1
View File
@@ -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}));