Format: number formats widen columns that weren't sized by hand (#1077)

Increase/Decrease Decimal and the ribbon's other number formats widened the format but never the
column, so the number turned into ####. A column nobody sized by hand now widens to the widest
number in the target, as observed in Excel 16.0: AutoFit counts as automatic, Column Width (or
dragging the border) as by hand; hidden columns, text, General numbers, merged and shrink-to-fit
cells don't widen; columns never narrow.

LineInfo::custom now marks columns set by hand too. XLSX reads and writes it as Excel does
(customWidth without bestFit = by hand; automatic widths get bestFit and customWidth), and .xls
reads COLINFO's fUserSet and fBestFit the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Vedran DobosandClaude Opus 5.5 committed 2026-10-22 07:21:26 +02:00
1 parent 06920de8da
commit f3a7c72bb6
11 files changed
+216 -7

No files matched your search

+116 -1
View File
@@ -708,7 +708,64 @@ fn number_format(s: &mut Session, p: &Json) -> Result<Json> {
fn set_fmt(s: &mut Session, p: &Json, code: &str) -> Result<Json> {
let nf = NumFmt::new(code);
apply_style(s, p, |st| st.num_fmt = nf.clone())
apply_style(s, p, |st| st.num_fmt = nf.clone())?;
widen_for_numbers(s, p)
}
/// After a number format from the ribbon (Increase Decimal, Comma Style, the Number Format list…),
/// a column nobody sized by hand widens so the formatted numbers in the target fit, instead of
/// showing ####. Observed in Excel 16.0 (build 17932): a column at the default width, AutoFitted, or
/// widened this way before widens to the widest number in the range, also with Wrap Text and a large
/// font. A width set with Column Width (or by dragging) stays, even when it equals the default. Hidden
/// columns, text, General numbers (they round to fit), shrink-to-fit and merged cells don't widen,
/// and columns never narrow.
fn widen_for_numbers(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let ranges = target_ranges(s, p)?;
let measure = s.text_width.clone();
edit(s, |cx| {
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(Json::Null) };
let Some(used) = sh.used_range() else { return Ok(Json::Null) };
if sh.show_formulas {
return Ok(Json::Null);
}
let mut need: std::collections::BTreeMap<u32, f32> = std::collections::BTreeMap::new();
// Measured as AutoFit Column Width measures (the UI's font when it supplies one).
let mut measured: std::collections::HashMap<(StyleId, String), f32> = Default::default();
for r in ranges.iter().filter_map(|r| r.intersection(&used)) {
if r.count() > 4_000_000 {
continue;
}
for (c, cell) in sh.cells.iter_range(r) {
if !matches!(cell.value, gridcraft_core::Value::Number(_))
|| sh.cols.get(&c.col).is_some_and(|i| i.custom || i.hidden)
|| sh.merge_at(c).is_some_and(|m| !m.is_single())
{
continue;
}
let id = sh.style_id(c);
let st = cx.wb.styles.get(id);
if st.num_fmt.as_str() == "General" || st.align.shrink || st.align.h == HAlign::Fill {
continue;
}
let text = crate::display::cell_text(&cx.wb, sh, c);
let exact = measured.len() < EXACT_TEXT_WIDTHS;
let w = *measured.entry((id, text)).or_insert_with_key(|(_, t)| match &measure {
Some(m) => m(t, &st.font, exact),
None => approx_text_width(t, st.font.size, st.font.bold),
});
let w = w + 6.0 + st.align.indent as f32 * 9.0;
let e = need.entry(c.col).or_insert(0.0);
*e = e.max(w);
}
}
let widen: Vec<(u32, f32)> = need.into_iter().filter(|&(c, w)| w > sh.col_width(c)).collect();
let sh = cx.sheet_mut(sheet)?;
for (c, w) in widen {
sh.cols.entry(c).or_default().size = Some(w.ceil().min(1785.0));
}
Ok(Json::Null)
})
}
/// Adds or removes one decimal place in the number format (Increase/Decrease Decimal).
@@ -1076,6 +1133,7 @@ fn col_width(s: &mut Session, p: &Json) -> Result<Json> {
let e = sh.cols.entry(c).or_default();
e.size = Some(w as f32);
e.hidden = w == 0.0;
e.custom = true;
}
}
Ok(Json::Null)
@@ -1167,6 +1225,7 @@ fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
let e = sh.cols.entry(c).or_default();
e.size = Some(w.ceil());
e.hidden = false;
e.custom = false; // AutoFit makes a width set by hand automatic again (Excel).
}
Ok(Json::Null)
})
@@ -1260,6 +1319,62 @@ mod tests {
assert_eq!(adjust_decimals("0%", &v, 1), "0.0%");
}
fn col(s: &crate::Session, c: u32) -> (f32, bool) {
let sh = s.active().unwrap().wb.active().unwrap();
(sh.col_width(c), sh.cols.get(&c).is_some_and(|i| i.custom))
}
/// #1077: Increase Decimal widened the format but not the column, so the number turned into ####.
#[test]
fn increase_decimal_widens_a_column_nobody_sized() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "3.14159265"})).unwrap();
let (default, _) = col(&s, 0);
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
let (w, custom) = col(&s, 0);
let text = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["text"].as_str().unwrap().to_string();
assert_eq!(text, "3.141592650");
assert!(w > default, "the column widens for {text}: {w} vs {default}");
assert!(w >= approx_text_width(&text, gridcraft_model::DEFAULT_FONT_SIZE, false), "and fits it");
assert!(!custom, "it isn't a width set by hand, so it can widen again");
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
assert!(col(&s, 0).0 > w, "one more decimal, a little wider again");
let wide = col(&s, 0).0;
s.execute("home.decreaseDecimal", json!({"range": "A1"})).unwrap();
assert_eq!(col(&s, 0).0, wide, "fewer decimals don't narrow it");
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(col(&s, 0).0, w, "Undo takes back the format and the width in one step");
}
#[test]
fn number_formats_keep_a_width_set_by_hand_and_general_numbers_round_instead() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891, 1234567.891, 1234567.891]]})).unwrap();
s.execute("home.columnWidth", json!({"cols": "A:A", "width": 40})).unwrap();
assert_eq!(col(&s, 0), (40.0, true), "Column Width (and dragging the border) is a width set by hand");
s.execute("home.hideColumns", json!({"cols": "D:D"})).unwrap();
for a in ["A1", "B1", "D1"] {
s.execute("home.comma", json!({"range": a})).unwrap();
}
s.execute("home.numberFormat", json!({"range": "C1", "format": "General"})).unwrap();
let (default, _) = col(&s, 4);
assert_eq!(col(&s, 0), (40.0, true), "a width set by hand stays: the cell shows ####, as in Excel");
assert!(col(&s, 1).0 > default, "B widens for 1,234,567.89");
assert_eq!(col(&s, 2).0, default, "General rounds to fit instead");
assert_eq!(col(&s, 3).0, 0.0, "a hidden column stays hidden");
// AutoFit makes a width set by hand automatic again; Wrap Text doesn't stop the widening.
s.execute("home.autofitColumnWidth", json!({"cols": "A:A"})).unwrap();
assert!(!col(&s, 0).1);
s.execute("home.wrapText", json!({"range": "A1", "on": true})).unwrap();
let fitted = col(&s, 0).0;
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
assert!(col(&s, 0).0 > fitted, "after AutoFit, with Wrap Text, A widens again");
}
#[test]
fn format_cells_takes_the_documented_keys() {
let mut s = crate::Session::new();
+2 -1
View File
@@ -925,7 +925,8 @@ pub struct LineInfo {
pub outline: u8,
pub collapsed: bool,
pub style: Option<crate::style::StyleId>,
/// The size was set by the user (rows): automatic heights follow the content.
/// The size was set by the user. Rows without it follow their content's height; columns
/// without it widen when a number format makes their numbers wider (`home.increaseDecimal`…).
#[serde(default)]
pub custom: bool,
}
+33
View File
@@ -963,6 +963,39 @@ fn general_numbers_fit_by_the_cells_own_font() {
assert_eq!(texts.iter().filter(|t| t.starts_with('#')).count(), 1, "{texts:?}");
}
/// #1077: after Increase Decimal and the other ribbon number formats the column widens enough for
/// the real font, so the number is drawn instead of ####, at the default size and a large bold one.
#[test]
fn ribbon_number_formats_widen_the_column_enough_to_draw_the_number() {
let mut s = blank();
s.execute("range.setValues", json!({"range": "A1", "values": [[1.23456789, 1234567.891, 98765.4321], [0.5, 1, 2]]})).unwrap();
s.execute("home.fontSize", json!({"range": "C1", "size": 20})).unwrap();
s.execute("home.bold", json!({"range": "C1", "on": true})).unwrap();
for _ in 0..4 {
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
}
s.execute("home.comma", json!({"range": "B1"})).unwrap();
s.execute("home.numberFormat", json!({"range": "C1", "format": "Currency"})).unwrap();
s.execute("selection.set", json!({"cell": "E5"})).unwrap();
let want: Vec<String> =
["A1", "B1", "C1"].iter().map(|a| s.execute("cell.get", json!({"cell": a})).unwrap()["text"].as_str().unwrap().trim().to_string()).collect();
assert_eq!(want, ["1.234567890000", "1,234,567.89", "$98,765.43"]);
let h = harness(s);
let texts: Vec<String> = h
.output()
.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) => Some(t.galley.job.text.clone()),
_ => None,
})
.collect();
for t in &want {
assert!(texts.iter().any(|x| x.trim() == t), "{t} drawn in full: {texts:?}");
}
assert!(!texts.iter().any(|t| t.starts_with('#')), "no ####: {texts:?}");
}
fn text_shapes(shape: &egui::Shape, clip: egui::Rect, out: &mut Vec<(egui::epaint::TextShape, egui::Rect)>) {
match shape {
egui::Shape::Text(t) => out.push((t.clone(), clip)),
+3
View File
@@ -314,6 +314,9 @@ fn read_cols(cx: &Ctx<'_>, e: &El, sheet: &mut Sheet, remaining: &mut u64) -> Re
// A width without `customWidth` that equals the default is just the default.
if let Some(w) = c.attr_f64("width") {
let px = col_width_to_px(w);
// Excel writes customWidth for every width it stores, and bestFit as well for one that
// AutoFit or a number format sized: only customWidth without bestFit was set by hand.
info.custom = c.flag("customWidth", false) && !c.flag("bestFit", false);
if c.flag("customWidth", false) || px != sheet.default_col_width {
info.size = Some(px);
}
+3 -1
View File
@@ -250,8 +250,10 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> (
if i.hidden {
s.push_str(" hidden=\"1\"");
}
// As Excel writes them: a width that AutoFit or a number format sized is bestFit too, so
// it keeps widening when the file is opened again; one set by hand is customWidth only.
if i.size.is_some() {
s.push_str(" customWidth=\"1\"");
s.push_str(if i.custom { " customWidth=\"1\"" } else { " bestFit=\"1\" customWidth=\"1\"" });
}
if i.outline > 0 {
let _ = write!(s, " outlineLevel=\"{}\"", i.outline.min(7));
+23
View File
@@ -169,7 +169,9 @@ fn styles_theme_and_sizes() {
assert!(s.cols.get(&2).unwrap().hidden);
assert_eq!(s.cols.get(&2).unwrap().size, Some(145.0));
assert_eq!(s.cols.get(&2).unwrap().outline, 1);
assert!(s.cols.get(&2).unwrap().custom, "customWidth: a width set by hand");
assert_ne!(s.cols.get(&3).unwrap().style, None);
assert!(!s.cols.get(&3).unwrap().custom, "no customWidth: not set by hand");
assert_eq!(s.rows.get(&0).unwrap().size, Some(40.0));
let r2 = s.rows.get(&1).unwrap();
assert!(r2.hidden);
@@ -250,6 +252,27 @@ fn dxf_border_is_written_before_protection() {
assert!(b.is_some() && p.is_some() && b < p, "{dx}");
}
/// Which stored widths were set by hand, as Excel 16.0 treats them when a number format makes a
/// number wider (#1077): only customWidth without bestFit keeps its width; the others widen.
#[test]
fn column_widths_set_by_hand() {
let body = r#"<cols><col min="1" max="1" width="15"/><col min="2" max="2" width="15" customWidth="1"/>
<col min="3" max="3" width="15" bestFit="1"/><col min="4" max="4" width="15" bestFit="1" customWidth="1"/>
<col min="5" max="5" width="9.140625" customWidth="1"/></cols><sheetData/>"#;
let (wb, _) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
let s = wb.sheet(0).unwrap();
let custom: Vec<bool> = (0..5).map(|c| s.cols.get(&c).is_some_and(|i| i.custom)).collect();
assert_eq!(custom, [false, true, false, false, true]);
assert_eq!(s.col_width(4), s.default_col_width, "E: the default width, but set by hand");
// Written back the way Excel writes them.
let bytes = crate::write_xlsx(&wb).unwrap();
let mut pkg = crate::package::Package::open(&bytes).unwrap();
let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap();
let flags: Vec<(bool, bool)> =
sheet.child("cols").unwrap().kids("col").map(|c| (c.flag("customWidth", false), c.flag("bestFit", false))).collect();
assert_eq!(flags, [(true, true), (true, false), (true, true), (true, false)], "C and D are one run");
}
#[test]
fn strict_namespace_and_shared_strings() {
let ct = super::CT;
+2 -1
View File
@@ -103,7 +103,8 @@ fn sample() -> Workbook {
s.spill.insert(at("H3"), Value::Number(3.0));
s.cols.insert(0, LineInfo { size: Some(100.0), ..Default::default() });
s.cols.insert(1, LineInfo { size: Some(100.0), ..Default::default() });
// Column B was sized by hand (customWidth), A widened by itself; both come back as they were.
s.cols.insert(1, LineInfo { size: Some(100.0), custom: true, ..Default::default() });
s.cols.insert(3, LineInfo { hidden: true, outline: 1, ..Default::default() });
s.cols.insert(5, LineInfo { style: Some(money), ..Default::default() });
s.rows.insert(0, LineInfo { size: Some(30.0), ..Default::default() });
+1
View File
@@ -698,6 +698,7 @@ fn sheet_record(rec: &Record<'_>, st: &mut SheetState<'_>, budget: &mut Budget,
}
let mut info = LineInfo::default();
let px = col_width_to_px(f64::from(width) / 256.0);
info.custom = flags & 0x0002 != 0 && flags & 0x0004 == 0; // fUserSet without fBestFit
if flags & 0x0002 != 0 || px != st.sheet.default_col_width {
info.size = Some(px);
}
+29 -1
View File
@@ -79,4 +79,32 @@ to 115% or 100%. That's a large relative step at low zoom and a small one near 4
relative steps keep each notch feeling the same, and the doublings land on 25, 50, 100, 200 and
400%. The status bar's Zoom In / Zoom Out buttons and Ctrl+Alt+= / Ctrl+Alt+- keep their 10%
steps, so the wheel and the buttons now step differently. Whether they should share one ladder
(this one, Excel's, or another) is left to the maintainers.
(this one, Excel's, or another) is left to the maintainers.
## Number formats widen columns that weren't sized by hand (#1077)
Increase/Decrease Decimal and the ribbon's other number formats (the Number Format list, Accounting,
Percent, Comma) widen a column so the formatted numbers in the target fit, instead of showing `####`.
Microsoft's support article "Stop showing rounded numbers" says only that "the column width adjusts
automatically", so the rule comes from observing Excel 16.0 (build 17932, Windows) with synthetic
workbooks:
- A column at the default width, AutoFitted, or widened this way before widens to the widest number
in the formatted range, also with Wrap Text and a large bold font. It never narrows.
- A width set with Column Width (or by dragging the border) stays, even when it equals the default:
the number shows `####`. AutoFit makes such a column automatic again.
- Hidden columns, text, General numbers (they round to fit instead), merged cells and shrink-to-fit
cells don't widen.
- In XLSX, Excel writes `customWidth="1"` for every width it stores and adds `bestFit="1"` for widths
that AutoFit or a number format set. Only `customWidth` without `bestFit` is read as set by hand: a
width with no flags, `bestFit` alone, or both, keeps widening after the file is opened again.
`LineInfo::custom`, already used for rows set by hand, now marks columns set by hand too; GridCraft
writes and reads the two flags as Excel does (and `.xls` COLINFO's fUserSet and fBestFit alike).
Files that earlier GridCraft versions saved have `customWidth` without `bestFit` on every stored
width, so those columns open as set by hand and keep their width.
The engine has no font metrics, so the width is the same estimate AutoFit Column Width uses, which
errs on the wide side; a UI test checks that the real font then draws the number, not `####`.
Excel also widens when a number format is set another way (observed through the `NumberFormat`
property, as Format Cells sets it); GridCraft's Format Cells doesn't yet. That, and typing a number
into a formatted cell, are left for later.
+2 -1
View File
@@ -1,6 +1,6 @@
# File-format parity
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-21 · **Change:** minor (.xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-22 · **Change:** minor (XLSX and `.xls` column widths keep whether they were set by hand, so automatic ones still widen for wider number formats, #1077; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests.
Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h**
@@ -110,6 +110,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
| Date | Change | Summary |
|---|---|---|
| 2026-10-22 | minor | XLSX column widths: `customWidth` without `bestFit` is a width set by hand, others (AutoFit, widened by a number format) are automatic, as Excel 16.0 reads them; written the same way (`bestFit="1" customWidth="1"` for automatic widths). `.xls` reads COLINFO's fUserSet and fBestFit alike (#1077) |
| 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI `<img>`) and charts (inline SVG from the chart crate's drawing primitives, text included) at their anchors; the table uses the sheet's column widths and row heights when the sheet has either, and output for sheets without pictures or charts is unchanged |
| 2026-10-20 | trivial | XLSX shared strings: Japanese phonetic runs (ふりがな, `<rPh sb="…" eb="…">` with `<phoneticPr>`) are read into the workbook and written back next to the string with the same text, so an open + save no longer deletes them; bad offsets and readings are dropped with a warning, a `<phoneticPr>` without runs is kept on its own, and when duplicate `<si>` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) |
| 2026-10-20 | minor | A workbook theme's major/minor per-script typefaces (`<a:font script="Arab" typeface="…"/>`, also Hebr, Jpan and the rest) are read and written back in file order after `<a:cs>`; they were dropped before. A hostile file is held to 64 entries of 256 characters |
+2 -1
View File
@@ -1,6 +1,6 @@
# UI parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-21 · **Change:** minor (Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (ribbon number formats widen columns nobody sized by hand, #1077; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md).
**UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured
@@ -176,6 +176,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
| Date | Change | Summary |
|---|---|---|
| 2026-10-22 | minor | Increase/Decrease Decimal and the ribbon's other number formats (Number Format list, Accounting, Percent, Comma) widen a column nobody sized by hand so the numbers fit, instead of showing #### (#1077). As observed in Excel 16.0: AutoFit counts as automatic, Column Width or dragging the border as by hand; hidden columns, text, General numbers, merged and shrink-to-fit cells don't widen, and columns never narrow |
| 2026-10-21 | minor | Background error checking, first part (#1994): a constant whose text would be a number if typed (signs, thousands, currency, percent, exponent, parenthesised negative) gets Excel's green corner triangle; the active cell then shows a warning button whose menu names the problem and offers Convert to Number for the selection (`formulas.convertToNumber`). Dates, times and fractions kept as text and formula results are not flagged, as in Excel |
| 2026-10-21 | minor | Paste Special laid out as Excel's: Paste and Operation options each in two columns inside a frame, Skip blanks and Transpose side by side, Paste Link as a button that pastes references at once; labels translated (the generic form didn't translate them) and the window no longer runs past the screen |
| 2026-10-21 | minor | Form dialogs (conditional-format quick rules, New Name, Remove Duplicates, Text to Columns and every other `Dialog::form`) fit their content: OK and Cancel sit in a row under the last field instead of a right-to-left layout that took the screen's whole height and left the buttons floating halfway down |