mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-30 10:13:56 +01:00
Merge main into i18n-vi
Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com>
This commit is contained in:
commit
cb08a89917
14 files changed
+667
-183
No files matched your search
@@ -187,6 +187,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) |
|
||||
| 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) |
|
||||
| 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison |
|
||||
| 2026-10-14 | RATE matches Excel's solver: the same last iterate for slowly converging cases (about -100% when the future value is 0, instead of `#NUM!`) and `#NUM!` where Excel's iteration can't reach a very large rate |
|
||||
| 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift |
|
||||
| 2026-10-14 | Protect Sheet on a protected sheet: Home › Format, its keytips (HOP, RPS) and the tab menu now read Unprotect Sheet… and unprotect (straight away without a password); a protected sheet that forbids selecting locked (or unlocked) cells is enforced for clicks, arrows and Go To, and the Protect Sheet dialog has the select options (#1346) |
|
||||
| 2026-10-14 | `.xls` (Excel 97-2003) files open with their formatting: fonts, solid and pattern fills, borders (with diagonals), alignment (rotation, indent, wrap, shrink), locked and hidden cells, the workbook's custom colour palette, its Normal font and its user-defined cell styles |
|
||||
@@ -321,6 +322,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-14 | minor | XLSX dynamic-array `cm` metadata kept on save; progress log row |
|
||||
| 2026-10-14 | minor | Progress log: spill anchor reading its old spill area |
|
||||
| 2026-10-14 | minor | Progress log: formulas reading an array that loses a spill conflict |
|
||||
| 2026-10-14 | trivial | Progress log: RATE follows Excel's iteration |
|
||||
| 2026-10-13 | trivial | Progress log: More Colors… and Recent Colors in the colour menus (#928) |
|
||||
| 2026-10-13 | minor | Multi-level category axes (read, drawn, written); progress log row |
|
||||
| 2026-10-13 | trivial | Progress log: shared pictures written once on XLSX export (#985) |
|
||||
|
||||
@@ -737,6 +737,43 @@ mod tests {
|
||||
assert_eq!([look("A1"), look("A2")], [true, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_compare_with_cells_on_other_sheets() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "E1", "values": [["Suspended"], ["OK"], ["Terminated"], [7], [3]]})).unwrap();
|
||||
let rule = |r: serde_json::Value| json!({"range": "E1:E5", "rule": r});
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
rule(json!({"type": "cellIs", "operator": "equal", "value": "='Vehicle Range'!$A$8", "preset": "redText"})),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
rule(json!({"type": "cellIs", "operator": "equal", "value": "='Vehicle Range'!$A$9", "preset": "redText"})),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
rule(json!({"type": "expression", "formula": "=AND(ISNUMBER(E1),E1>'Vehicle Range'!$B$1)", "preset": "yellowFill"})),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("home.insertSheet", json!({"name": "Vehicle Range"})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "'Vehicle Range'!A8", "values": [["Suspended"], ["Terminated"]]})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "'Vehicle Range'!B1", "values": [[5]]})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let report = d.wb.sheets.iter().position(|sh| sh.name != "Vehicle Range").unwrap();
|
||||
let mut cache = CfCache::new();
|
||||
let mut look = |a: &str| cache.look(&d.wb, report, CellRef::parse(a).unwrap()).and_then(|l| l.style).unwrap_or_default();
|
||||
let looks = ["E1", "E2", "E3", "E4", "E5"].map(&mut look);
|
||||
// The cells equal to 'Vehicle Range'!A8 or A9 get the red text.
|
||||
let red_text = looks[0].font.color;
|
||||
assert_ne!(red_text, Color::Auto);
|
||||
let red = |st: &Style| st.font.color == red_text;
|
||||
let filled = |st: &Style| st.fill.pattern == PatternType::Solid;
|
||||
assert_eq!(looks.each_ref().map(red), [true, false, true, false, false]);
|
||||
assert_eq!(looks.each_ref().map(filled), [false, false, false, true, false]);
|
||||
}
|
||||
#[test]
|
||||
fn text_rules_skip_error_values() {
|
||||
let mut s = crate::Session::new();
|
||||
|
||||
@@ -33,6 +33,82 @@ fn tvm() {
|
||||
is_err(ev("CUMIPMT", vec![n(0.01), n(360.0), n(125000.0), n(1.0), n(1.0), n(2.0)]), CellError::Num);
|
||||
}
|
||||
|
||||
/// RATE with the given arguments, as a number or an error.
|
||||
fn rate_of(args: &[f64]) -> Value {
|
||||
ev("RATE", args.iter().map(|x| n(*x)).collect())
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn rate_is(args: &[f64], expected: f64) {
|
||||
close_tol(rate_of(args), expected, 1e-15);
|
||||
}
|
||||
|
||||
/// Expected values observed in Excel 365 with these synthetic inputs.
|
||||
#[test]
|
||||
fn rate_follows_excel_iteration() {
|
||||
// No payments and a zero future value: the answer is -100%, which the iteration
|
||||
// approaches without reaching. Excel returns the last iterate, bit for bit.
|
||||
rate_is(&[5.0, 0.0, -100.0, 0.0], -0.999_999_409_145_182_5);
|
||||
rate_is(&[3.0, 0.0, -50.0, 0.0], -0.999_999_744_782_979_9);
|
||||
rate_is(&[10.0, 0.0, -1.0, 0.0], -0.999_998_741_101_371_3);
|
||||
rate_is(&[5.0, 0.0, -100.0, 0.0, 0.0, 0.5], -0.999_999_408_783_809_4);
|
||||
rate_is(&[5.0, 0.0, -100.0, 0.0, 0.0, -0.99], -0.999_999_411_730_630_3);
|
||||
// Second starting point goes the other way when the equation is positive at the guess.
|
||||
rate_is(&[5.0, 0.0, 100.0, 0.0], -0.999_999_409_810_240_3);
|
||||
rate_is(&[5.0, 0.0, -100.0, 1e-29], -0.999_999_260_333_075_4);
|
||||
rate_is(&[5.0, 0.0, -100.0, 1e4], 1.511_886_431_510_563_3);
|
||||
rate_is(&[4.0, 0.0, -1.0, 100.0], 2.162_277_660_168_009);
|
||||
// Within 1e-7 by step but not by value: Excel keeps going.
|
||||
rate_is(&[5.0, 0.0, -1e25, 0.0], -0.999_999_628_525_605_1);
|
||||
// 200 steps without converging: the last iterate when it is within 1e-4, else #NUM!.
|
||||
rate_is(&[20.0, 0.0, -1.0, 0.0], -0.999_112_071_912_539_3);
|
||||
rate_is(&[36.0, 0.0, -1.0, 0.0, 0.0, -0.994], -0.999_875_315_309_626_9);
|
||||
is_err(rate_of(&[12.0, 0.0, -1.0, 0.0]), CellError::Num);
|
||||
is_err(rate_of(&[25.0, 0.0, -1.0, 0.0]), CellError::Num);
|
||||
is_err(rate_of(&[20.0, 0.0, -1e60, 0.0]), CellError::Num);
|
||||
// Large rates the iteration can't reach are #NUM! in Excel.
|
||||
is_err(rate_of(&[4.0, 0.0, -0.0001, 100.0]), CellError::Num);
|
||||
is_err(rate_of(&[5.0, 0.0, -100.0, 1e5]), CellError::Num);
|
||||
is_err(rate_of(&[10.0, -300.0, 1000.0]), CellError::Num);
|
||||
// ...but are found from a closer guess.
|
||||
rate_is(&[4.0, 0.0, -0.1, 100.0, 0.0, 4.0], 4.623_413_251_903_489);
|
||||
close_tol(rate_of(&[10.0, -300.0, 1000.0, 0.0, 0.0, 0.3]), 0.273_198_424_105_560_4, 1e-12);
|
||||
// Converging on a rate at or below -100% (or within 1e-7 of it) is #NUM!.
|
||||
is_err(rate_of(&[1.0, 0.0, -1.0, 0.0]), CellError::Num);
|
||||
is_err(rate_of(&[10.0, -1000.0, 1000.0]), CellError::Num);
|
||||
is_err(rate_of(&[1.0, 0.0, -100.0, 1e-5]), CellError::Num);
|
||||
rate_is(&[1.0, 0.0, -100.0, 2e-5], -0.999_999_8);
|
||||
is_err(rate_of(&[5.0, 0.0, -1e30, 0.0]), CellError::Num);
|
||||
is_err(rate_of(&[0.5, 0.0, -1.0, 0.0]), CellError::Num);
|
||||
// A value that never gets near zero is #NUM!, however small the step.
|
||||
is_err(rate_of(&[4.0, 0.0, 100.0, 100.0]), CellError::Num);
|
||||
is_err(rate_of(&[4.0, 0.0, -1e-12, 1e-6]), CellError::Num);
|
||||
rate_is(&[4.0, 0.0, -1e-14, 1e-8], 0.099_000_000_283_235_72);
|
||||
// Subnormal steps are flushed to zero.
|
||||
rate_is(&[3.0, 0.0, -1e-305, 0.0], 0.101);
|
||||
is_err(rate_of(&[4.0, 0.0, 0.0, 100.0]), CellError::Num);
|
||||
// Guess at or below -1 is #VALUE!; type is 0 or anything else (1).
|
||||
is_err(rate_of(&[10.0, -100.0, 1000.0, 0.0, 0.0, -1.0]), CellError::Value);
|
||||
is_err(rate_of(&[0.0, -100.0, 1000.0]), CellError::Num);
|
||||
// Excel does not step the second point back to -1: a fractional nper with a guess near -1 is #NUM!
|
||||
// even though a root exists at -0.99, and the same case from a guess of -0.99 finds it.
|
||||
is_err(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.9995]), CellError::Num);
|
||||
is_err(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.5]), CellError::Num);
|
||||
close_tol(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.99]), -0.99, 1e-7);
|
||||
assert_eq!(rate_of(&[10.0, -100.0, 1000.0, 0.0, 2.0]), rate_of(&[10.0, -100.0, 1000.0, 0.0, 1.0]));
|
||||
// Ordinary loans, and large amounts that can't get within 1e-7 of zero.
|
||||
close_tol(rate_of(&[360.0, -1000.0, 150000.0]), 0.005_850_253_376_759_637, 1e-11);
|
||||
close_tol(rate_of(&[360.0, -1000.0, 150000.0, 0.0, 1.0]), 0.005_898_953_457_098_463, 1e-11);
|
||||
close_tol(rate_of(&[1000.0, -1e6, 1e8]), 0.009_999_522_655_994_865, 1e-12);
|
||||
close_tol(rate_of(&[360.0, -1e9, 1.5e11]), 0.005_850_253_376_759_668, 1e-12);
|
||||
close_tol(rate_of(&[10.0, -50.0, 1000.0]), -0.109_560_293_684_682_5, 1e-14);
|
||||
// Roots at 0% come out as rounding noise in both, so only the absolute size matters.
|
||||
match rate_of(&[10.0, -100.0, 1000.0]) {
|
||||
Value::Number(x) => assert!(x.abs() < 1e-8, "{x}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// PMT within about 4 ULPs of Excel's (Value2 of synthetic probes; libm differs by an ULP across
|
||||
/// platforms). The old `(1 + rate)^nper` form was 25 to 91 ULPs off on these, enough to flip a loan schedule's final `IF(p - SUM(r) > 0, ...)`.
|
||||
#[test]
|
||||
|
||||
@@ -218,21 +218,85 @@ fn solve_rate(f: impl Fn(f64) -> f64, guess: f64) -> R<f64> {
|
||||
Err(CellError::Num)
|
||||
}
|
||||
|
||||
/// RATE's equation at rate `r`: the loan and the payments grown to the end of the term, plus
|
||||
/// `fv`. RATE returns the rate where it is zero. The second value is the size of its terms, to
|
||||
/// judge how close to zero the first can get in floating point.
|
||||
fn rate_equation(r: f64, np: f64, pmt: f64, pv: f64, fv: f64, typ: f64) -> (f64, f64) {
|
||||
if r == 0.0 {
|
||||
return (pv + pmt * np + fv, pv.abs() + (pmt * np).abs() + fv.abs());
|
||||
}
|
||||
let p = (1.0 + r).powf(np);
|
||||
let (a, b) = (pv * p, pmt * (1.0 / r + typ) * (p - 1.0));
|
||||
(a + b + fv, a.abs() + b.abs() + fv.abs())
|
||||
}
|
||||
|
||||
/// Excel works with subnormal numbers flushed to zero: a secant step that underflows doesn't
|
||||
/// move. Observed with RATE(3,0,-1E-305,0), which is 0.101 (the second starting point).
|
||||
fn flush_subnormal(x: f64) -> f64 {
|
||||
if x.abs() < f64::MIN_POSITIVE { 0.0 } else { x }
|
||||
}
|
||||
|
||||
/// Excel's RATE solver, reconstructed by observing Excel with synthetic inputs (not from its
|
||||
/// code; its documentation says only "iteration", 20 steps and 0.0000001):
|
||||
///
|
||||
/// - A secant iteration starting at the guess and at the guess moved 0.001 toward a larger
|
||||
/// value of the equation, for at most 200 steps.
|
||||
/// - It stops at the first iterate that moved less than 1e-7 and where the equation is within
|
||||
/// 1e-7 of zero (or as close as its terms allow, for very large amounts). Excel returns that
|
||||
/// iterate, not the exact root, so a slowly converging case such as no payments and a zero
|
||||
/// future value (exact answer -100%) gives a rate just above -1.
|
||||
/// - The result must be above -1 by more than the tolerance; otherwise it is #NUM!.
|
||||
/// - After 200 steps without that, Excel still returns the last iterate if it is within a
|
||||
/// looser 1e-4 (step, equation value and distance above -1); otherwise #NUM!. So a root the
|
||||
/// iteration can't reach (a very large rate) is #NUM! even though it exists.
|
||||
fn rate_solve(f: impl Fn(f64) -> (f64, f64), guess: f64) -> R<f64> {
|
||||
const STEPS: usize = 200;
|
||||
const TOL: f64 = 1e-7;
|
||||
const LOOSE: f64 = 1e-4;
|
||||
let eval = |x: f64| {
|
||||
let (y, size) = f(x);
|
||||
if y.is_finite() { Ok((y, size)) } else { Err(CellError::Num) }
|
||||
};
|
||||
let near_zero = |y: f64, size: f64| y.abs() < TOL || y.abs() <= 1e-12 * size;
|
||||
let (mut x0, (mut f0, _)) = (guess, eval(guess)?);
|
||||
let mut x1 = if f0 < 0.0 { guess + 0.001 } else { guess - 0.001 };
|
||||
let (mut f1, mut size1) = eval(x1)?;
|
||||
for _ in 0..STEPS {
|
||||
let den = flush_subnormal(f1 - f0);
|
||||
if den == 0.0 {
|
||||
// The secant is flat: done if the iteration had already settled.
|
||||
if (x1 - x0).abs() < TOL && near_zero(f1, size1) && x1 - TOL > -1.0 {
|
||||
return Ok(x1);
|
||||
}
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let x2 = x1 - flush_subnormal(f1 * (x1 - x0)) / den;
|
||||
if !x2.is_finite() {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let (f2, size2) = eval(x2)?;
|
||||
if (x2 - x1).abs() < TOL && near_zero(f2, size2) {
|
||||
return if x2 - TOL > -1.0 { Ok(x2) } else { Err(CellError::Num) };
|
||||
}
|
||||
(x0, f0, x1, f1, size1) = (x1, f1, x2, f2, size2);
|
||||
}
|
||||
if (x1 - x0).abs() < LOOSE && f1.abs() < LOOSE && x1 - LOOSE > -1.0 {
|
||||
return Ok(x1);
|
||||
}
|
||||
Err(CellError::Num)
|
||||
}
|
||||
|
||||
pub(super) fn rate(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let (np, pmt, pv) = (num(a, 0)?, num(a, 1)?, num(a, 2)?);
|
||||
let (fv, typ, guess) = (opt_num(a, 3, 0.0)?, type_arg(a, 4)?, opt_num(a, 5, 0.1)?);
|
||||
if np <= 0.0 {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let f = |r: f64| {
|
||||
if r.abs() < 1e-12 {
|
||||
pv + pmt * np + fv
|
||||
} else {
|
||||
let p = (1.0 + r).powf(np);
|
||||
pv * p + pmt * (1.0 + r * typ) * (p - 1.0) / r + fv
|
||||
}
|
||||
};
|
||||
num_val(solve_rate(f, guess)?)
|
||||
// Excel: a guess at or below -100% is #VALUE!, not #NUM!.
|
||||
if guess <= -1.0 {
|
||||
return Err(CellError::Value);
|
||||
}
|
||||
num_val(rate_solve(|r| rate_equation(r, np, pmt, pv, fv, typ), guess)?)
|
||||
}
|
||||
|
||||
pub(super) fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
|
||||
@@ -8,7 +8,7 @@ use gridcraft_core::{CellError, CellRef, DateSystem, MAX_COLS, MAX_ROWS, RangeRe
|
||||
use gridcraft_formula::Expr;
|
||||
use gridcraft_model::{
|
||||
AutoFilter, Cell, CfOperator, CfRule, CfValueKind, Comment, CondFormat, EditRange, ErrorStyle, FilterCriterion, Formula, Hyperlink, LineInfo,
|
||||
NoteBox, NoteCorner, Orientation, PageOrder, PasswordHash, Sheet, SheetProtection, Sparkline, SparklineKind, Table, TableColumn, TotalsFn,
|
||||
NoteBox, NoteCorner, Orientation, PageOrder, PasswordHash, Sheet, SheetProtection, Sparkline, SparklineKind, Style, Table, TableColumn, TotalsFn,
|
||||
Validation, ValidationKind, XmlColumnPr,
|
||||
};
|
||||
|
||||
@@ -25,7 +25,7 @@ mod rules;
|
||||
|
||||
pub use parts::{read_autofilter, read_table};
|
||||
use parts::{read_comments, read_hyperlinks, read_note_shapes, read_threaded};
|
||||
use rules::{read_cf, read_validation};
|
||||
use rules::{read_cf, read_validation, read_x14_cf};
|
||||
|
||||
struct Shared {
|
||||
anchor: CellRef,
|
||||
@@ -344,7 +344,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr
|
||||
}
|
||||
}
|
||||
}
|
||||
"extLst" => read_ext(cx, e, &mut sheet),
|
||||
"extLst" => read_ext(cx, e, &mut sheet, &mut cf_kept_cells),
|
||||
"protectedRanges" => read_protected_ranges(e, &mut sheet),
|
||||
_ => {}
|
||||
}
|
||||
@@ -850,7 +850,7 @@ pub fn parse_sqref(s: Option<&str>) -> Vec<RangeRef> {
|
||||
}
|
||||
|
||||
/// Worksheet extensions: x14 data validations and sparklines.
|
||||
fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) {
|
||||
fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, cf_kept_cells: &mut u64) {
|
||||
for ext in e.kids("ext") {
|
||||
for c in &ext.children {
|
||||
match c.name.as_str() {
|
||||
@@ -878,23 +878,7 @@ fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) {
|
||||
}
|
||||
}
|
||||
}
|
||||
"conditionalFormattings" => {
|
||||
let mut skipped = false;
|
||||
for r in c.kids("conditionalFormatting").flat_map(|f| f.kids("cfRule")) {
|
||||
let idx = r.attr("id").and_then(|id| cx.cf_ext_ids.iter().find(|(i, _)| i == id)).map(|(_, n)| *n);
|
||||
match (idx.and_then(|n| sheet.cond_formats.get_mut(n)), r.child("dataBar")) {
|
||||
(Some(CondFormat { rule: CfRule::DataBar { gradient, .. }, .. }), Some(db)) => {
|
||||
*gradient = db.flag("gradient", true);
|
||||
// Only the fill style is modelled; borders, lengths, axis or negative colours are lost.
|
||||
skipped |= db.attrs.iter().any(|(k, _)| k != "gradient") || db.children.iter().any(|k| k.name != "cfvo");
|
||||
}
|
||||
_ => skipped = true,
|
||||
}
|
||||
}
|
||||
if skipped {
|
||||
cx.warn("some Excel 2010 conditional format extensions were skipped");
|
||||
}
|
||||
}
|
||||
"conditionalFormattings" => read_x14_cf(cx, c, sheet, cf_kept_cells),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::{
|
||||
CfOperator, CfRule, CfValueKind, CondFormat, Ctx, El, ErrorStyle, MAX_COND_CELLS, RangeRef, Sheet, Validation, ValidationKind, from_file,
|
||||
CfOperator, CfRule, CfValueKind, CondFormat, Ctx, El, ErrorStyle, MAX_COND_CELLS, RangeRef, Sheet, Style, Validation, ValidationKind, from_file,
|
||||
parse_sqref, read_color,
|
||||
};
|
||||
|
||||
@@ -57,79 +57,164 @@ pub(super) fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, kept_cells: &
|
||||
for r in e.kids("cfRule") {
|
||||
let style = Box::new(r.attr_u32("dxfId").and_then(|i| cx.dxfs.get(i as usize)).cloned().unwrap_or_default());
|
||||
let formulas: Vec<String> = r.kids("formula").map(|f| from_file(f.text.trim())).collect();
|
||||
let f0 = formulas.first().cloned().unwrap_or_default();
|
||||
let text = r.attr("text").unwrap_or("").to_string();
|
||||
// The x14 id that links a data bar to its Excel 2010 extension (solid fill lives there).
|
||||
let ext_id =
|
||||
r.child("extLst").and_then(|l| l.kids("ext").find_map(|x| x.child("id"))).map(|i| i.text.trim().to_string()).filter(|i| !i.is_empty());
|
||||
let rule = match r.attr("type").unwrap_or("") {
|
||||
"cellIs" => CfRule::CellIs { op: cf_op(r.attr("operator")), a: f0, b: formulas.get(1).cloned(), style },
|
||||
"expression" => CfRule::Expression { formula: f0, style },
|
||||
"containsText" => CfRule::ContainsText { text, style },
|
||||
"notContainsText" => CfRule::NotContainsText { text, style },
|
||||
"beginsWith" => CfRule::BeginsWith { text, style },
|
||||
"endsWith" => CfRule::EndsWith { text, style },
|
||||
"containsBlanks" => CfRule::Blanks { style },
|
||||
"notContainsBlanks" => CfRule::NoBlanks { style },
|
||||
"containsErrors" => CfRule::Errors { style },
|
||||
"notContainsErrors" => CfRule::NoErrors { style },
|
||||
"duplicateValues" => CfRule::Duplicate { style },
|
||||
"uniqueValues" => CfRule::Unique { style },
|
||||
"top10" => {
|
||||
CfRule::Top10 { bottom: r.flag("bottom", false), percent: r.flag("percent", false), rank: r.attr_u32("rank").unwrap_or(10), style }
|
||||
}
|
||||
"aboveAverage" => CfRule::AboveAverage {
|
||||
below: !r.flag("aboveAverage", true),
|
||||
equal: r.flag("equalAverage", false),
|
||||
std_dev: r.attr_u32("stdDev").unwrap_or(0).min(3) as u8,
|
||||
style,
|
||||
},
|
||||
"timePeriod" => CfRule::TimePeriod { period: r.attr("timePeriod").unwrap_or("today").to_string(), style },
|
||||
"colorScale" => {
|
||||
let Some(cs) = r.child("colorScale") else { continue };
|
||||
let colors = cs.kids("color").map(|c| read_color(c, &cx.palette));
|
||||
CfRule::ColorScale { stops: cfvos(cs).into_iter().zip(colors).collect() }
|
||||
}
|
||||
"dataBar" => {
|
||||
let Some(db) = r.child("dataBar") else { continue };
|
||||
let v = cfvos(db);
|
||||
CfRule::DataBar {
|
||||
min: v.first().cloned().unwrap_or(CfValueKind::Min),
|
||||
max: v.get(1).cloned().unwrap_or(CfValueKind::Max),
|
||||
color: db.child("color").map(|c| read_color(c, &cx.palette)).unwrap_or_default(),
|
||||
gradient: true,
|
||||
show_value: db.flag("showValue", true),
|
||||
let ty = r.attr("type").unwrap_or("");
|
||||
match cf_rule(cx, r, ty, formulas, style) {
|
||||
Some(rule) => {
|
||||
if !push_cf(cx, sheet, &ranges, block_cells, r, rule, kept_cells) {
|
||||
break;
|
||||
}
|
||||
if let Some(id) = ext_id {
|
||||
cx.cf_ext_ids.push((id, sheet.cond_formats.len() - 1));
|
||||
}
|
||||
}
|
||||
"iconSet" => {
|
||||
let Some(is) = r.child("iconSet") else { continue };
|
||||
CfRule::IconSet {
|
||||
set: is.attr("iconSet").unwrap_or("3TrafficLights1").to_string(),
|
||||
thresholds: cfvos(is),
|
||||
reverse: is.flag("reverse", false),
|
||||
show_value: is.flag("showValue", true),
|
||||
}
|
||||
None if matches!(ty, "colorScale" | "dataBar" | "iconSet") => {}
|
||||
None => cx.warn(format!("conditional format type \"{ty}\" is not supported")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_cf(cx: &mut Ctx<'_>, sheet: &mut Sheet, ranges: &[RangeRef], block_cells: u64, r: &El, rule: CfRule, kept_cells: &mut u64) -> bool {
|
||||
let total = kept_cells.saturating_add(block_cells);
|
||||
if total > MAX_COND_CELLS {
|
||||
cx.warn(format!("conditional formats past {MAX_COND_CELLS} kept range cells were dropped"));
|
||||
return false;
|
||||
}
|
||||
*kept_cells = total;
|
||||
sheet.cond_formats.push(CondFormat {
|
||||
ranges: ranges.to_vec(),
|
||||
rule,
|
||||
priority: r.attr_u32("priority").unwrap_or(0),
|
||||
stop_if_true: r.flag("stopIfTrue", false),
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// The rule of a `cfRule` (main namespace or x14) of type `ty`, given its formulas and
|
||||
/// differential style; `None` for an unknown type or a scale, bar or icon set without its body.
|
||||
fn cf_rule(cx: &Ctx<'_>, r: &El, ty: &str, formulas: Vec<String>, style: Box<Style>) -> Option<CfRule> {
|
||||
let mut formulas = formulas.into_iter();
|
||||
let f0 = formulas.next().unwrap_or_default();
|
||||
let text = r.attr("text").unwrap_or("").to_string();
|
||||
Some(match ty {
|
||||
"cellIs" => CfRule::CellIs { op: cf_op(r.attr("operator")), a: f0, b: formulas.next(), style },
|
||||
"expression" => CfRule::Expression { formula: f0, style },
|
||||
"containsText" => CfRule::ContainsText { text, style },
|
||||
"notContainsText" => CfRule::NotContainsText { text, style },
|
||||
"beginsWith" => CfRule::BeginsWith { text, style },
|
||||
"endsWith" => CfRule::EndsWith { text, style },
|
||||
"containsBlanks" => CfRule::Blanks { style },
|
||||
"notContainsBlanks" => CfRule::NoBlanks { style },
|
||||
"containsErrors" => CfRule::Errors { style },
|
||||
"notContainsErrors" => CfRule::NoErrors { style },
|
||||
"duplicateValues" => CfRule::Duplicate { style },
|
||||
"uniqueValues" => CfRule::Unique { style },
|
||||
"top10" => {
|
||||
CfRule::Top10 { bottom: r.flag("bottom", false), percent: r.flag("percent", false), rank: r.attr_u32("rank").unwrap_or(10), style }
|
||||
}
|
||||
"aboveAverage" => CfRule::AboveAverage {
|
||||
below: !r.flag("aboveAverage", true),
|
||||
equal: r.flag("equalAverage", false),
|
||||
std_dev: r.attr_u32("stdDev").unwrap_or(0).min(3) as u8,
|
||||
style,
|
||||
},
|
||||
"timePeriod" => CfRule::TimePeriod { period: r.attr("timePeriod").unwrap_or("today").to_string(), style },
|
||||
"colorScale" => {
|
||||
let cs = r.child("colorScale")?;
|
||||
let colors = cs.kids("color").map(|c| read_color(c, &cx.palette));
|
||||
CfRule::ColorScale { stops: cfvos(cs).into_iter().zip(colors).collect() }
|
||||
}
|
||||
"dataBar" => {
|
||||
let db = r.child("dataBar")?;
|
||||
let v = cfvos(db);
|
||||
CfRule::DataBar {
|
||||
min: v.first().cloned().unwrap_or(CfValueKind::Min),
|
||||
max: v.get(1).cloned().unwrap_or(CfValueKind::Max),
|
||||
color: db.child("color").map(|c| read_color(c, &cx.palette)).unwrap_or_default(),
|
||||
gradient: true,
|
||||
show_value: db.flag("showValue", true),
|
||||
}
|
||||
other => {
|
||||
cx.warn(format!("conditional format type \"{other}\" is not supported"));
|
||||
}
|
||||
"iconSet" => {
|
||||
let is = r.child("iconSet")?;
|
||||
CfRule::IconSet {
|
||||
set: is.attr("iconSet").unwrap_or("3TrafficLights1").to_string(),
|
||||
thresholds: cfvos(is),
|
||||
reverse: is.flag("reverse", false),
|
||||
show_value: is.flag("showValue", true),
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `x14:conditionalFormattings` (MS-XLSX 2.4.6): rules kept out of the main section, such as
|
||||
/// those whose formulas refer to other sheets in the one LibreOffice-saved file seen. They carry
|
||||
/// `xm:f` formulas, an inline `x14:dxf` and priorities shared with the main-section rules.
|
||||
/// Read: cellIs, expression, (not)containsBlanks, (not)containsErrors, duplicate/unique values,
|
||||
/// top10, aboveAverage and timePeriod. The x14 extension a main-section data bar links to by
|
||||
/// `x14:id` adds no rule, only that bar's solid fill (its other settings are skipped with a
|
||||
/// warning). Skipped with a warning (and so lost on save): other data bars, icon sets, colour
|
||||
/// scales and the text rules containsText, notContainsText, beginsWith and endsWith.
|
||||
pub(super) fn read_x14_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, kept_cells: &mut u64) {
|
||||
for cf in e.kids("conditionalFormatting") {
|
||||
let ranges = parse_sqref(cf.child("sqref").map(|s| s.text.as_str()));
|
||||
let block_cells = ranges.iter().map(RangeRef::count).fold(0u64, u64::saturating_add);
|
||||
for r in cf.kids("cfRule") {
|
||||
let ty = r.attr("type").unwrap_or("");
|
||||
let linked = r.attr("id").and_then(|id| cx.cf_ext_ids.iter().find(|(i, _)| i == id.trim())).map(|(_, n)| *n);
|
||||
if let Some(n) = linked {
|
||||
match (sheet.cond_formats.get_mut(n), r.child("dataBar")) {
|
||||
(Some(CondFormat { rule: CfRule::DataBar { gradient, .. }, .. }), Some(db)) => {
|
||||
*gradient = db.flag("gradient", true);
|
||||
// Only the fill style is modelled, with negatives in the bar's colour and no axis;
|
||||
// borders, lengths, other axis positions or negative colours are lost.
|
||||
let modelled = |k: &str, v: &str| {
|
||||
k == "gradient"
|
||||
|| (k == "axisPosition" && v == "none")
|
||||
|| (k == "negativeBarColorSameAsPositive" && matches!(v, "1" | "true"))
|
||||
};
|
||||
if db.attrs.iter().any(|(k, v)| !modelled(k, v)) || db.children.iter().any(|k| k.name != "cfvo") {
|
||||
cx.warn(format!("Excel 2010 conditional format extension \"{ty}\" was partly skipped (only its solid fill is kept)"));
|
||||
}
|
||||
}
|
||||
_ => cx.warn(format!("Excel 2010 conditional format extension \"{ty}\" was skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let total = kept_cells.saturating_add(block_cells);
|
||||
if total > MAX_COND_CELLS {
|
||||
cx.warn(format!("conditional formats past {MAX_COND_CELLS} kept range cells were dropped"));
|
||||
break;
|
||||
if ranges.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Only rule kinds whose formulas are kept and written back here; the others' x14
|
||||
// forms add settings (bar fills and axes, custom icons) the model doesn't hold.
|
||||
let supported = matches!(
|
||||
ty,
|
||||
"cellIs"
|
||||
| "expression"
|
||||
| "containsBlanks"
|
||||
| "notContainsBlanks"
|
||||
| "containsErrors"
|
||||
| "notContainsErrors"
|
||||
| "duplicateValues"
|
||||
| "uniqueValues"
|
||||
| "top10"
|
||||
| "aboveAverage"
|
||||
| "timePeriod"
|
||||
);
|
||||
if !supported {
|
||||
cx.warn(format!("Excel 2010 conditional format extension \"{ty}\" was skipped"));
|
||||
continue;
|
||||
}
|
||||
let style = Box::new(r.child("dxf").map(|x| crate::styles::read_x14_dxf(x, &cx.palette, &cx.num_fmts)).unwrap_or_default());
|
||||
let formulas: Vec<String> = r.kids("f").map(|f| from_file(f.text.trim())).collect();
|
||||
if let Some(rule) = cf_rule(cx, r, ty, formulas, style)
|
||||
&& !push_cf(cx, sheet, &ranges, block_cells, r, rule, kept_cells)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
*kept_cells = total;
|
||||
if let Some(id) = ext_id {
|
||||
cx.cf_ext_ids.push((id, sheet.cond_formats.len()));
|
||||
}
|
||||
sheet.cond_formats.push(CondFormat {
|
||||
ranges: ranges.clone(),
|
||||
rule,
|
||||
priority: r.attr_u32("priority").unwrap_or(0),
|
||||
stop_if_true: r.flag("stopIfTrue", false),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,19 +11,23 @@ use gridcraft_model::{
|
||||
|
||||
use crate::drawing::{Obj, image_content_type, image_ext};
|
||||
use crate::fmla::text_to_file;
|
||||
use crate::styles::{color_attrs, dxf_id};
|
||||
use crate::styles::{color_attrs, dxf_id, dxf_xml};
|
||||
use crate::tables::{paper_id, px_to_col_width, px_to_pt};
|
||||
use crate::write::{
|
||||
CT_CHART, CT_COMMENTS, CT_DRAWING, CT_TABLE, CT_THREADED_COMMENTS, NS_MAIN, NS_REL, NS_THREADED, Out, REL_THREADED_COMMENT, Rels, XML_DECL,
|
||||
x14_cf_rule_guid,
|
||||
};
|
||||
use crate::xml::{encode_xstring, esc, esc_attr, num, push_a1, push_u64};
|
||||
|
||||
/// The worksheet extension holding Excel 2010 conditional formats.
|
||||
const EXT_X14_CF: &str = "{78C0D931-6437-407d-A8EE-F0AAD7539E65}";
|
||||
|
||||
mod parts;
|
||||
mod rules;
|
||||
|
||||
pub(crate) use parts::password_attrs;
|
||||
use parts::{autofilter_xml, comments_xml, protected_ranges_xml, table_columns, table_name, table_xml, thread_ids, threaded_xml, vml_xml};
|
||||
use rules::{cf_rule_xml, solid_bar_id, validation_xml, x14_cfvo};
|
||||
use rules::{cf_rule_xml, solid_bar_x14, validation_xml, x14_cf_rule_xml};
|
||||
|
||||
fn sqref(ranges: &[RangeRef]) -> String {
|
||||
ranges.iter().map(|r| r.a1()).collect::<Vec<_>>().join(" ")
|
||||
@@ -193,7 +197,7 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> (
|
||||
|
||||
write_sheet_data(&mut s, SheetCellData { workbook: wb, index: si, sheet, overrides: &overrides, extra: &extra, dynamic: &dynamic }, &sid, out);
|
||||
|
||||
let prio = write_sheet_rules(&mut s, sheet, &mut rels, out);
|
||||
let x14_cf = write_sheet_rules(&mut s, sheet, &mut rels, out);
|
||||
let kept = write_sheet_printing(&mut s, sheet, &mut rels, out);
|
||||
|
||||
write_sheet_drawing(&mut s, wb, si, sheet, &mut rels, out);
|
||||
@@ -214,7 +218,7 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> (
|
||||
}
|
||||
let _ = write!(s, "<tableParts count=\"{}\">{parts}</tableParts>", tables.len());
|
||||
}
|
||||
write_sheet_extensions(&mut s, sheet, &prio);
|
||||
write_sheet_extensions(&mut s, sheet, &x14_cf);
|
||||
s.push_str("</worksheet>");
|
||||
(s, rels)
|
||||
}
|
||||
@@ -228,31 +232,13 @@ struct CellWriteInput<'a> {
|
||||
dynamic_range: Option<&'a RangeRef>,
|
||||
}
|
||||
|
||||
fn write_sheet_extensions(s: &mut String, sheet: &Sheet, prio: &[u32]) {
|
||||
// Excel 2010 extensions: solid data bars, then sparklines.
|
||||
let solid_bars: Vec<(&CondFormat, u32)> = sheet
|
||||
.cond_formats
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, cf)| !cf.ranges.is_empty() && matches!(cf.rule, CfRule::DataBar { gradient: false, .. }))
|
||||
.map(|(i, cf)| (cf, prio.get(i).copied().unwrap_or(1)))
|
||||
.collect();
|
||||
if !solid_bars.is_empty() || !sheet.sparklines.is_empty() {
|
||||
fn write_sheet_extensions(s: &mut String, sheet: &Sheet, x14_cf: &str) {
|
||||
// Excel 2010 extensions: conditional formats, then sparklines.
|
||||
if !x14_cf.is_empty() || !sheet.sparklines.is_empty() {
|
||||
s.push_str("<extLst>");
|
||||
}
|
||||
if !solid_bars.is_empty() {
|
||||
let _ = write!(
|
||||
s,
|
||||
"<ext uri=\"{{78C0D931-6437-407d-A8A1-0F90B4350D7D}}\" xmlns:x14=\"{X14_NS}\" xmlns:xm=\"{XM_NS}\"><x14:conditionalFormattings>"
|
||||
);
|
||||
for (cf, p) in &solid_bars {
|
||||
if let CfRule::DataBar { min, max, .. } = &cf.rule {
|
||||
let (id, lo, hi) = (solid_bar_id(*p), x14_cfvo(min), x14_cfvo(max));
|
||||
let _ = write!(s, "<x14:conditionalFormatting><x14:cfRule type=\"dataBar\" id=\"{id}\"><x14:dataBar gradient=\"0\">{lo}{hi}");
|
||||
let _ = write!(s, "</x14:dataBar></x14:cfRule><xm:sqref>{}</xm:sqref></x14:conditionalFormatting>", sqref(&cf.ranges));
|
||||
}
|
||||
}
|
||||
s.push_str("</x14:conditionalFormattings></ext>");
|
||||
if !x14_cf.is_empty() {
|
||||
let _ = write!(s, "<ext uri=\"{EXT_X14_CF}\" xmlns:x14=\"{X14_NS}\"><x14:conditionalFormattings>{x14_cf}</x14:conditionalFormattings></ext>");
|
||||
}
|
||||
if !sheet.sparklines.is_empty() {
|
||||
let _ = write!(s, "<ext uri=\"{{05C60535-1F16-4fd2-B633-F4F36F0B64E0}}\" xmlns:x14=\"{X14_NS}\"><x14:sparklineGroups xmlns:xm=\"{XM_NS}\">");
|
||||
@@ -275,7 +261,7 @@ fn write_sheet_extensions(s: &mut String, sheet: &Sheet, prio: &[u32]) {
|
||||
}
|
||||
s.push_str("</x14:sparklineGroups></ext>");
|
||||
}
|
||||
if !solid_bars.is_empty() || !sheet.sparklines.is_empty() {
|
||||
if !x14_cf.is_empty() || !sheet.sparklines.is_empty() {
|
||||
s.push_str("</extLst>");
|
||||
}
|
||||
}
|
||||
@@ -470,7 +456,7 @@ fn write_sheet_printing<'a>(s: &mut String, sheet: &'a Sheet, rels: &mut Rels, o
|
||||
kept
|
||||
}
|
||||
|
||||
fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut Out) -> Vec<u32> {
|
||||
fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut Out) -> String {
|
||||
// sheetProtection
|
||||
if let Some(p) = &sheet.protection {
|
||||
s.push_str("<sheetProtection sheet=\"1\" objects=\"1\" scenarios=\"1\"");
|
||||
@@ -524,16 +510,34 @@ fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut O
|
||||
*p = rank as u32 + 1;
|
||||
}
|
||||
}
|
||||
// Cell-value and formula rules referring to another sheet go to the Excel 2010 extension.
|
||||
// Excel for Mac 16.114 also writes cross-sheet expression rules there (the tested synthetic
|
||||
// files opened without a repair prompt), using this URI. It stores cross-sheet cfvo rules for
|
||||
// colour scales, data bars and icon sets only in x14; GridCraft writes those in the main
|
||||
// section, and drops x14-only forms on read with a warning. GridCraft-written test files with
|
||||
// those main-section rules also opened without a repair prompt.
|
||||
// A solid data bar is in both sections: the extension holds its fill.
|
||||
let mut x14_cf = String::new();
|
||||
for (i, cf) in sheet.cond_formats.iter().enumerate() {
|
||||
if cf.ranges.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let _ = write!(
|
||||
s,
|
||||
"<conditionalFormatting sqref=\"{}\">{}</conditionalFormatting>",
|
||||
sqref(&cf.ranges),
|
||||
cf_rule_xml(cf, prio.get(i).copied().unwrap_or(1), out)
|
||||
);
|
||||
let priority = prio.get(i).copied().unwrap_or(1);
|
||||
let x14 = match x14_cf_rule_xml(cf, &sheet.name, priority, out) {
|
||||
Some(rule) => Some(rule),
|
||||
None => {
|
||||
let _ =
|
||||
write!(s, "<conditionalFormatting sqref=\"{}\">{}</conditionalFormatting>", sqref(&cf.ranges), cf_rule_xml(cf, priority, out));
|
||||
solid_bar_x14(cf, priority)
|
||||
}
|
||||
};
|
||||
if let Some(rule) = x14 {
|
||||
let _ = write!(
|
||||
x14_cf,
|
||||
"<x14:conditionalFormatting xmlns:xm=\"{XM_NS}\">{rule}<xm:sqref>{}</xm:sqref></x14:conditionalFormatting>",
|
||||
sqref(&cf.ranges)
|
||||
);
|
||||
}
|
||||
}
|
||||
let vals: Vec<&Validation> = sheet.validations.iter().filter(|v| !v.ranges.is_empty()).collect();
|
||||
if !vals.is_empty() {
|
||||
@@ -578,7 +582,7 @@ fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut O
|
||||
}
|
||||
s.push_str("</hyperlinks>");
|
||||
}
|
||||
prio
|
||||
x14_cf
|
||||
}
|
||||
|
||||
struct SheetCellData<'a> {
|
||||
|
||||
@@ -183,6 +183,60 @@ pub(super) fn cf_rule_xml(cf: &CondFormat, priority: u32, out: &mut Out) -> Stri
|
||||
}
|
||||
}
|
||||
|
||||
/// The x14 rule a solid data bar's `cfRule` links to (it holds the fill); `None` for other rules.
|
||||
/// GridCraft draws negative values in the bar's colour from the low end, with no axis; the x14
|
||||
/// defaults are an automatic axis and a separate negative colour, so both are written out.
|
||||
pub(super) fn solid_bar_x14(cf: &CondFormat, priority: u32) -> Option<String> {
|
||||
let CfRule::DataBar { min, max, gradient: false, .. } = &cf.rule else { return None };
|
||||
let (id, lo, hi) = (solid_bar_id(priority), x14_cfvo(min), x14_cfvo(max));
|
||||
Some(format!(
|
||||
"<x14:cfRule type=\"dataBar\" id=\"{id}\"><x14:dataBar gradient=\"0\" negativeBarColorSameAsPositive=\"1\" axisPosition=\"none\">{lo}{hi}</x14:dataBar></x14:cfRule>"
|
||||
))
|
||||
}
|
||||
|
||||
/// Whether formula `f` refers to a sheet other than `own`, and whether it refers to a 3-D span of
|
||||
/// sheets.
|
||||
fn sheet_refs(f: &str, own: &str) -> (bool, bool) {
|
||||
let Ok(e) = gridcraft_formula::parse(f.trim_start_matches('=')) else { return (false, false) };
|
||||
let refs = e.references();
|
||||
let other = refs.iter().any(|r| match &r.sheet {
|
||||
gridcraft_formula::SheetSel::Named(n) => !n.chars().flat_map(char::to_lowercase).eq(own.chars().flat_map(char::to_lowercase)),
|
||||
_ => false,
|
||||
});
|
||||
let span = refs.iter().any(|r| matches!(r.sheet, gridcraft_formula::SheetSel::Span(..)));
|
||||
(other, span)
|
||||
}
|
||||
|
||||
/// The Excel 2010 form (`x14:cfRule`, `xm:f` formulas, inline `x14:dxf`) of a cell-value or
|
||||
/// formula rule that refers to another sheet; `None` for rules that belong in the main section.
|
||||
/// MS-XLSX 2.6.27 (CT_CfRule) forbids 3-D spans (`sheet-range-reference`) in `xm:f`, so a rule
|
||||
/// with one stays in the main section.
|
||||
pub(super) fn x14_cf_rule_xml(cf: &CondFormat, own: &str, priority: u32, out: &mut Out) -> Option<String> {
|
||||
let (ty, extra, formulas, style): (&str, String, Vec<&str>, &Style) = match &cf.rule {
|
||||
CfRule::CellIs { op, a, b, style } => {
|
||||
("cellIs", format!(" operator=\"{}\"", cf_op_name(*op)), std::iter::once(a.as_str()).chain(b.as_deref()).collect(), style)
|
||||
}
|
||||
CfRule::Expression { formula, style } => ("expression", String::new(), vec![formula.as_str()], style),
|
||||
_ => return None,
|
||||
};
|
||||
let refs: Vec<(bool, bool)> = formulas.iter().map(|f| sheet_refs(f, own)).collect();
|
||||
if !refs.iter().any(|&(other, _)| other) || refs.iter().any(|&(_, span)| span) {
|
||||
return None;
|
||||
}
|
||||
out.x14_cf_rules += 1;
|
||||
let mut s = format!(
|
||||
"<x14:cfRule type=\"{ty}\" priority=\"{priority}\"{}{extra} id=\"{}\">",
|
||||
if cf.stop_if_true { " stopIfTrue=\"1\"" } else { "" },
|
||||
x14_cf_rule_guid(out.x14_cf_rules)
|
||||
);
|
||||
for f in formulas {
|
||||
let _ = write!(s, "<xm:f>{}</xm:f>", esc(&text_to_file(f)));
|
||||
}
|
||||
s.push_str(&dxf_xml("x14:dxf", style, &mut out.num_fmts));
|
||||
s.push_str("</x14:cfRule>");
|
||||
Some(s)
|
||||
}
|
||||
|
||||
fn validation_formula(f: &str) -> String {
|
||||
let f = f.trim();
|
||||
if f.starts_with('"') {
|
||||
|
||||
+61
-46
@@ -444,6 +444,14 @@ fn read_dxf<'a>(x: &'a El, palette: &[u32], fmts: &HashMap<u32, NumFmt>, inline_
|
||||
s
|
||||
}
|
||||
|
||||
/// An inline Excel 2010 `x14:dxf` differential format, resolving `numFmtId` against `cx.num_fmts`.
|
||||
pub fn read_x14_dxf(x: &El, palette: &[u32], fmts: &HashMap<u32, String>) -> Style {
|
||||
let shared: HashMap<u32, NumFmt> =
|
||||
x.child("numFmt").and_then(|n| n.attr_u32("numFmtId")).and_then(|id| fmts.get(&id).map(|c| (id, NumFmt::new(c)))).into_iter().collect();
|
||||
let mut inline_fmts = HashMap::new();
|
||||
read_dxf(x, palette, &shared, &mut inline_fmts)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- writing
|
||||
|
||||
pub fn color_attrs(c: &Color) -> String {
|
||||
@@ -639,14 +647,16 @@ fn intern<T: Clone + Eq + std::hash::Hash>(list: &mut Vec<T>, map: &mut HashMap<
|
||||
i
|
||||
}
|
||||
|
||||
/// Number format ids assigned while writing.
|
||||
struct NumFmts {
|
||||
/// Number format ids assigned while writing. Worksheets that carry inline differential formats
|
||||
/// (`x14:dxf`) assign ids first, through [`crate::write::Out`]; `styles.xml` lists them all.
|
||||
#[derive(Default)]
|
||||
pub struct NumFmts {
|
||||
custom: Vec<(u32, String)>,
|
||||
map: HashMap<String, u32>,
|
||||
}
|
||||
|
||||
impl NumFmts {
|
||||
fn id(&mut self, code: &str) -> u32 {
|
||||
pub fn id(&mut self, code: &str) -> u32 {
|
||||
if let Some(id) = builtin_id(code) {
|
||||
return id;
|
||||
}
|
||||
@@ -662,10 +672,10 @@ impl NumFmts {
|
||||
|
||||
/// `styles.xml` for the workbook: one cell format per model style, in `StyleId` order (so a
|
||||
/// cell's `s` attribute is its style id), plus the given differential formats.
|
||||
/// `extra_fmts` are number formats used outside cell styles (PivotTable value fields); the
|
||||
/// returned map gives the id of every custom format written.
|
||||
pub fn write_styles(wb: &Workbook, dxfs: &[Style], extra_fmts: &[String]) -> (String, HashMap<String, u32>) {
|
||||
let mut nf = NumFmts { custom: vec![], map: HashMap::new() };
|
||||
/// `extra_fmts` are number formats used outside cell styles (PivotTable value fields); `nf`
|
||||
/// holds the ids worksheets already assigned. The returned map gives the id of every custom
|
||||
/// format written.
|
||||
pub fn write_styles(wb: &Workbook, dxfs: &[Style], extra_fmts: &[String], mut nf: NumFmts) -> (String, HashMap<String, u32>) {
|
||||
let mut fonts: Vec<Font> = vec![];
|
||||
let mut font_map = HashMap::new();
|
||||
let mut fills: Vec<Fill> = vec![Fill::default(), Fill { pattern: PatternType::Gray125, fg: Color::Auto, bg: Color::Auto }];
|
||||
@@ -745,44 +755,7 @@ pub fn write_styles(wb: &Workbook, dxfs: &[Style], extra_fmts: &[String]) -> (St
|
||||
|
||||
let mut dx = String::new();
|
||||
for d in dxfs {
|
||||
dx.push_str("<dxf>");
|
||||
let def = Style::default();
|
||||
let st = &d.dxf_stated;
|
||||
if d.font.bold
|
||||
|| d.font.italic
|
||||
|| d.font.strike
|
||||
|| d.font.underline != Underline::None
|
||||
|| d.font.color != Color::Auto
|
||||
|| d.font.vert != VertAlign::Baseline
|
||||
|| d.font.size != def.font.size
|
||||
|| d.font.name != def.font.name
|
||||
|| st.bold
|
||||
|| st.italic
|
||||
|| st.strike
|
||||
|| st.underline
|
||||
|| st.size
|
||||
|| st.name
|
||||
|| st.scheme.is_some()
|
||||
{
|
||||
dx.push_str(&font_xml(&d.font, Some(st), false));
|
||||
}
|
||||
if d.num_fmt != def.num_fmt {
|
||||
let id = nf.id(d.num_fmt.as_str());
|
||||
let _ = write!(dx, "<numFmt numFmtId=\"{id}\" formatCode=\"{}\"/>", esc_attr(d.num_fmt.as_str()));
|
||||
}
|
||||
if d.fill != def.fill {
|
||||
dx.push_str(&fill_xml(&d.fill, true));
|
||||
}
|
||||
if let Some(a) = alignment_xml(&d.align) {
|
||||
dx.push_str(&a);
|
||||
}
|
||||
if d.borders != def.borders {
|
||||
dx.push_str(&border_xml(&d.borders));
|
||||
}
|
||||
if st.protection || d.protection != def.protection {
|
||||
let _ = write!(dx, "<protection locked=\"{}\" hidden=\"{}\"/>", d.protection.locked as u8, d.protection.hidden as u8);
|
||||
}
|
||||
dx.push_str("</dxf>");
|
||||
dx.push_str(&dxf_xml("dxf", d, &mut nf));
|
||||
}
|
||||
for f in extra_fmts {
|
||||
nf.id(f);
|
||||
@@ -820,6 +793,48 @@ pub fn write_styles(wb: &Workbook, dxfs: &[Style], extra_fmts: &[String]) -> (St
|
||||
(s, nf.map)
|
||||
}
|
||||
|
||||
/// A differential format element named `tag` (`dxf`, or `x14:dxf` inline in a worksheet rule).
|
||||
pub fn dxf_xml(tag: &str, d: &Style, nf: &mut NumFmts) -> String {
|
||||
let mut dx = format!("<{tag}>");
|
||||
let def = Style::default();
|
||||
if d.font.bold
|
||||
|| d.font.italic
|
||||
|| d.font.strike
|
||||
|| d.font.underline != Underline::None
|
||||
|| d.font.color != Color::Auto
|
||||
|| d.font.vert != VertAlign::Baseline
|
||||
|| d.font.size != def.font.size
|
||||
|| d.font.name != def.font.name
|
||||
|| d.dxf_stated.bold
|
||||
|| d.dxf_stated.italic
|
||||
|| d.dxf_stated.strike
|
||||
|| d.dxf_stated.underline
|
||||
|| d.dxf_stated.size
|
||||
|| d.dxf_stated.name
|
||||
|| d.dxf_stated.scheme.is_some()
|
||||
{
|
||||
dx.push_str(&font_xml(&d.font, Some(&d.dxf_stated), false));
|
||||
}
|
||||
if d.num_fmt != def.num_fmt {
|
||||
let id = nf.id(d.num_fmt.as_str());
|
||||
let _ = write!(dx, "<numFmt numFmtId=\"{id}\" formatCode=\"{}\"/>", esc_attr(d.num_fmt.as_str()));
|
||||
}
|
||||
if d.fill != def.fill {
|
||||
dx.push_str(&fill_xml(&d.fill, true));
|
||||
}
|
||||
if let Some(a) = alignment_xml(&d.align) {
|
||||
dx.push_str(&a);
|
||||
}
|
||||
if d.borders != def.borders {
|
||||
dx.push_str(&border_xml(&d.borders));
|
||||
}
|
||||
if d.dxf_stated.protection || d.protection != def.protection {
|
||||
let _ = write!(dx, "<protection locked=\"{}\" hidden=\"{}\"/>", d.protection.locked as u8, d.protection.hidden as u8);
|
||||
}
|
||||
let _ = write!(dx, "</{tag}>");
|
||||
dx
|
||||
}
|
||||
|
||||
/// Index of a differential format, adding it when new.
|
||||
pub fn dxf_id(dxfs: &mut Vec<Style>, s: &Style) -> u32 {
|
||||
if let Some(i) = dxfs.iter().position(|d| d == s) {
|
||||
@@ -856,7 +871,7 @@ mod tests {
|
||||
let mut wb = Workbook::new();
|
||||
wb.styles.intern(styles.xfs[1].clone());
|
||||
wb.cell_styles = styles.named.clone();
|
||||
let (xml, _) = write_styles(&wb, &styles.dxfs, &[]);
|
||||
let (xml, _) = write_styles(&wb, &styles.dxfs, &[], NumFmts::default());
|
||||
let root = crate::xml::parse(xml.as_bytes()).unwrap();
|
||||
for section in ["dxfs", "cellXfs", "cellStyleXfs"] {
|
||||
let orders: Vec<_> = root
|
||||
|
||||
@@ -1014,6 +1014,139 @@ fn icon_sets_always_write_one_cfvo_per_icon() {
|
||||
assert_eq!(rules, [3, 4, 5]);
|
||||
}
|
||||
|
||||
const X14_CF_SHEET: &str = r#"<sheetData/>
|
||||
<conditionalFormatting sqref="B1:B5"><cfRule type="dataBar" priority="2"><dataBar><cfvo type="min"/><cfvo type="max"/><color rgb="FF638EC6"/></dataBar><extLst><ext uri="{B025F937-C7B1-47D3-B67F-A62EFF666E3E}" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"><x14:id>{00000000-0000-0000-0000-00000000000A}</x14:id></ext></extLst></cfRule></conditionalFormatting>
|
||||
<extLst><ext uri="{78C0D931-6437-407d-A8EE-F0AAD7539E65}" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"><x14:conditionalFormattings>
|
||||
<x14:conditionalFormatting xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main">
|
||||
<x14:cfRule type="cellIs" priority="3" operator="between" id="{00000000-0000-0000-0000-000000000001}"><xm:f>Lists!$A$1</xm:f><xm:f>Lists!$A$2</xm:f><x14:dxf><font><b/><color rgb="FF4F5051"/></font><numFmt numFmtId="170" formatCode="0.0%"/><fill><patternFill><bgColor rgb="FFFFC7CE"/></patternFill></fill><border><left style="thin"><color rgb="FF000000"/></left></border></x14:dxf></x14:cfRule>
|
||||
<x14:cfRule type="expression" priority="1" stopIfTrue="1" id="{00000000-0000-0000-0000-000000000002}"><xm:f>A1=Lists!$B$1</xm:f><x14:dxf><fill><patternFill><bgColor rgb="FFFFEB9C"/></patternFill></fill></x14:dxf></x14:cfRule>
|
||||
<xm:sqref>A1:A10 C1</xm:sqref></x14:conditionalFormatting>
|
||||
<x14:conditionalFormatting xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main"><x14:cfRule type="dataBar" id="{00000000-0000-0000-0000-00000000000A}"><x14:dataBar minLength="0" maxLength="100" gradient="0"><x14:cfvo type="autoMin"/><x14:cfvo type="autoMax"/></x14:dataBar></x14:cfRule><xm:sqref>B1:B5</xm:sqref></x14:conditionalFormatting>
|
||||
<x14:conditionalFormatting xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main"><x14:cfRule type="iconSet" priority="4" id="{00000000-0000-0000-0000-000000000003}"><x14:iconSet iconSet="3Stars"><x14:cfvo type="percent"><xm:f>0</xm:f></x14:cfvo><x14:cfvo type="percent"><xm:f>33</xm:f></x14:cfvo><x14:cfvo type="percent"><xm:f>67</xm:f></x14:cfvo></x14:iconSet></x14:cfRule><xm:sqref>D1:D3</xm:sqref></x14:conditionalFormatting>
|
||||
</x14:conditionalFormattings></ext></extLst>"#;
|
||||
|
||||
/// Rules in the `x14:conditionalFormattings` extension (such as those referring to other sheets)
|
||||
/// carry `xm:f` formulas and an inline `x14:dxf`; their priorities interleave with the main
|
||||
/// section's. A data bar's linked extension adds no rule, only the bar's solid fill (its other
|
||||
/// settings are skipped with a warning); x14 icon sets are skipped with a warning.
|
||||
#[test]
|
||||
fn x14_conditional_formats_are_read() {
|
||||
let (wb, rep) = read_xlsx(&super::minimal(X14_CF_SHEET, &[], "", "")).unwrap();
|
||||
let mut cfs = wb.sheet(0).unwrap().cond_formats.clone();
|
||||
cfs.sort_by_key(|cf| cf.priority);
|
||||
assert_eq!(cfs.iter().map(|cf| cf.priority).collect::<Vec<_>>(), [1, 2, 3], "{cfs:?}");
|
||||
let [expr, bar, cell] = &cfs[..] else { panic!("{cfs:?}") };
|
||||
assert_eq!(expr.ranges, [rr("A1:A10"), rr("C1")]);
|
||||
assert!(expr.stop_if_true);
|
||||
match &expr.rule {
|
||||
CfRule::Expression { formula, style } => {
|
||||
assert_eq!(formula, "A1=Lists!$B$1");
|
||||
assert_eq!(style.fill, Fill::solid(Color::Rgb(0xFFEB9C)));
|
||||
}
|
||||
r => panic!("{r:?}"),
|
||||
}
|
||||
assert!(matches!(bar.rule, CfRule::DataBar { gradient: false, .. }), "{bar:?}");
|
||||
assert_eq!(bar.ranges, [rr("B1:B5")]);
|
||||
match &cell.rule {
|
||||
CfRule::CellIs { op, a, b, style } => {
|
||||
assert_eq!((*op, a.as_str(), b.as_deref()), (CfOperator::Between, "Lists!$A$1", Some("Lists!$A$2")));
|
||||
assert!(style.font.bold);
|
||||
assert_eq!(style.font.color, Color::Rgb(0x4F5051));
|
||||
assert_eq!(style.num_fmt.as_str(), "0.0%");
|
||||
assert_eq!(style.fill, Fill::solid(Color::Rgb(0xFFC7CE)));
|
||||
assert_eq!(style.borders.left.style, BorderStyle::Thin);
|
||||
}
|
||||
r => panic!("{r:?}"),
|
||||
}
|
||||
// Unsupported x14 kinds still warn, by name; nothing else does.
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("\"dataBar\"")), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("\"iconSet\"")), "{:?}", rep.warnings);
|
||||
assert_eq!(rep.warnings.iter().filter(|w| w.contains("conditional format")).count(), 2, "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
/// A rule referring to another sheet is written in the x14 extension (as the LibreOffice-saved
|
||||
/// file that motivated this places it), ahead of the sparklines in the one `extLst`; other rules
|
||||
/// stay in the main section, and so does a rule with a 3-D span, which MS-XLSX 2.6.27 forbids in
|
||||
/// `xm:f`.
|
||||
#[test]
|
||||
fn cross_sheet_rules_are_written_in_the_x14_extension() {
|
||||
let mut wb = Workbook::new();
|
||||
wb.sheets.push(Arc::new(Sheet::new("Vehicle Range")));
|
||||
let grey = Style { font: Font { color: Color::Rgb(0x4F5051), ..Style::default().font }, num_fmt: NumFmt::new("0.0%"), ..Style::default() };
|
||||
let s = wb.sheet_mut(0).unwrap();
|
||||
let rules = [
|
||||
(CfRule::Expression { formula: "E1>Sheet1!$B$1".into(), style: Box::new(grey.clone()) }, false),
|
||||
(CfRule::CellIs { op: CfOperator::Equal, a: "'Vehicle Range'!$A$8".into(), b: None, style: Box::new(grey.clone()) }, true),
|
||||
(CfRule::CellIs { op: CfOperator::Greater, a: "5".into(), b: None, style: Box::new(grey.clone()) }, false),
|
||||
(CfRule::Expression { formula: "SUM('Sheet1:Vehicle Range'!$A$1)>0".into(), style: Box::new(grey) }, false),
|
||||
];
|
||||
for (i, (rule, stop_if_true)) in rules.into_iter().enumerate() {
|
||||
s.cond_formats.push(CondFormat { ranges: vec![rr("E1:E20")], rule, priority: i as u32 + 1, stop_if_true });
|
||||
}
|
||||
s.sparklines.push(Sparkline { cell: at("J2"), source: "B2:B3".into(), kind: SparklineKind::Line, color: Color::Auto, markers: false });
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
let (xml, _) = sheet1_xml(&bytes);
|
||||
let (main, ext) = xml.split_once("<extLst>").unwrap();
|
||||
assert_eq!(main.matches("<cfRule ").count(), 3, "{main}");
|
||||
assert!(!main.contains("$A$8"), "{main}");
|
||||
assert!(main.contains("<formula>E1>Sheet1!$B$1</formula>"), "{main}");
|
||||
assert!(main.contains("<formula>SUM('Sheet1:Vehicle Range'!$A$1)>0</formula>"), "{main}");
|
||||
assert_eq!(ext.matches("<x14:cfRule ").count(), 1, "{ext}");
|
||||
assert_eq!(ext.matches("<extLst>").count(), 0, "one extLst: {ext}");
|
||||
let cf = ext.find("{78C0D931-6437-407d-A8EE-F0AAD7539E65}").unwrap();
|
||||
assert!(cf < ext.find("{05C60535-1F16-4fd2-B633-F4F36F0B64E0}").unwrap(), "conditional formats before sparklines: {ext}");
|
||||
assert!(ext.contains("xmlns:x14=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main\""), "{ext}");
|
||||
assert!(ext.contains("<x14:conditionalFormatting xmlns:xm=\"http://schemas.microsoft.com/office/excel/2006/main\">"), "{ext}");
|
||||
assert!(ext.contains("<x14:cfRule type=\"cellIs\" priority=\"2\" stopIfTrue=\"1\" operator=\"equal\" id=\"{"), "{ext}");
|
||||
assert!(ext.contains("<xm:f>'Vehicle Range'!$A$8</xm:f><x14:dxf><font><color rgb=\"FF4F5051\"/></font><numFmt numFmtId=\""), "{ext}");
|
||||
assert!(ext.contains("</x14:dxf></x14:cfRule><xm:sqref>E1:E20</xm:sqref></x14:conditionalFormatting>"), "{ext}");
|
||||
// The inline number format's id is the one `styles.xml` declares for its code.
|
||||
let id = ext.split("<numFmt numFmtId=\"").nth(1).and_then(|r| r.split('"').next()).unwrap();
|
||||
let mut styles = String::new();
|
||||
zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap().by_name("xl/styles.xml").unwrap().read_to_string(&mut styles).unwrap();
|
||||
assert!(styles.contains(&format!("<numFmt numFmtId=\"{id}\" formatCode=\"0.0%\"/>")), "{styles}");
|
||||
|
||||
let (back, rep) = read_xlsx(&bytes).unwrap();
|
||||
assert!(rep.warnings.is_empty(), "{:?}", rep.warnings);
|
||||
let mut got = back.sheet(0).unwrap().cond_formats.clone();
|
||||
got.sort_by_key(|cf| cf.priority);
|
||||
assert_eq!(got, wb.sheet(0).unwrap().cond_formats);
|
||||
}
|
||||
|
||||
/// A differential format's protection is written after its alignment and border (the CT_Dxf
|
||||
/// order: font, numFmt, fill, alignment, border, protection), both inline in an `x14:dxf` and in `styles.xml`, and reads back.
|
||||
#[test]
|
||||
fn dxf_protection_is_written_in_schema_order() {
|
||||
let mut wb = Workbook::new();
|
||||
wb.sheets.push(Arc::new(Sheet::new("Other")));
|
||||
let mut st = Style { fill: Fill::solid(Color::Rgb(0xFFC7CE)), ..Style::default() };
|
||||
st.align.h = HAlign::Center;
|
||||
st.protection = gridcraft_model::style::Protection { locked: false, hidden: true };
|
||||
st.borders.left.style = BorderStyle::Thin;
|
||||
let s = wb.sheet_mut(0).unwrap();
|
||||
let rules = [
|
||||
CfRule::Expression { formula: "A1=Other!$A$1".into(), style: Box::new(st.clone()) },
|
||||
CfRule::Expression { formula: "A1>5".into(), style: Box::new(st) },
|
||||
];
|
||||
for (i, rule) in rules.into_iter().enumerate() {
|
||||
s.cond_formats.push(CondFormat { ranges: vec![rr("A1:A5")], rule, priority: i as u32 + 1, stop_if_true: false });
|
||||
}
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
let (xml, _) = sheet1_xml(&bytes);
|
||||
let mut styles = String::new();
|
||||
zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap().by_name("xl/styles.xml").unwrap().read_to_string(&mut styles).unwrap();
|
||||
let dxfs = &styles[styles.find("<dxfs").unwrap()..];
|
||||
for part in [xml.as_str(), dxfs] {
|
||||
let p = part.find("<protection locked=\"0\" hidden=\"1\"/>").unwrap_or_else(|| panic!("{part}"));
|
||||
assert!(part.find("<alignment").unwrap() < part.find("<border>").unwrap() && part.find("<border>").unwrap() < p, "{part}");
|
||||
}
|
||||
let (back, rep) = read_xlsx(&bytes).unwrap();
|
||||
assert!(rep.warnings.is_empty(), "{:?}", rep.warnings);
|
||||
let mut got = back.sheet(0).unwrap().cond_formats.clone();
|
||||
got.sort_by_key(|cf| cf.priority);
|
||||
assert_eq!(got, wb.sheet(0).unwrap().cond_formats);
|
||||
}
|
||||
|
||||
/// Files have no `@` operator. An `@` that legacy Excel implies is written without it in a
|
||||
/// legacy formula (no dynamic-array metadata); any other `@x` is written as `_xlfn.SINGLE(x)`
|
||||
/// in a dynamic-array formula. Both read back as written in the model.
|
||||
@@ -1698,6 +1831,11 @@ fn solid_data_bar_survives_with_sparklines_and_gradient_neighbours() {
|
||||
// x14 cfvo values are `xm:f` children; a `val` attribute there is not valid x14.
|
||||
let (xml, _) = sheet1_xml(&bytes);
|
||||
assert!(xml.contains("<x14:cfvo type=\"num\"><xm:f>9</xm:f></x14:cfvo>"), "{xml}");
|
||||
// Both solid bars sit in the one x14 conditional format extension, under its MS-XLSX uri.
|
||||
assert_eq!(xml.matches("<ext uri=\"{78C0D931-6437-407d-A8EE-F0AAD7539E65}\"").count(), 1, "{xml}");
|
||||
assert_eq!(xml.matches("<x14:cfRule type=\"dataBar\"").count(), 2, "{xml}");
|
||||
// As drawn here: negatives in the bar's colour, no axis (Excel's x14 defaults differ), and read back without a warning.
|
||||
assert_eq!(xml.matches("<x14:dataBar gradient=\"0\" negativeBarColorSameAsPositive=\"1\" axisPosition=\"none\">").count(), 2, "{xml}");
|
||||
let (back, rep) = read_xlsx(&bytes).unwrap();
|
||||
assert!(rep.warnings.is_empty(), "{:?}", rep.warnings);
|
||||
let b = &back.sheets[0];
|
||||
|
||||
@@ -111,6 +111,10 @@ pub struct Out {
|
||||
overrides: Vec<(String, String)>,
|
||||
defaults: BTreeMap<String, String>,
|
||||
pub dxfs: Vec<Style>,
|
||||
/// Number format ids assigned so far (inline `x14:dxf` formats); `styles.xml` adds the rest.
|
||||
pub num_fmts: crate::styles::NumFmts,
|
||||
/// Excel 2010 conditional format rules written so far (each needs a unique id).
|
||||
pub x14_cf_rules: u32,
|
||||
pub sst: Sst,
|
||||
pub images: u32,
|
||||
/// Media parts written so far, by extension and SHA-256 of their bytes: a picture used again
|
||||
@@ -181,6 +185,12 @@ pub fn person_guid(i: usize) -> String {
|
||||
format!("{{00000000-0000-4000-8002-{:012X}}}", i as u64 & 0xFFFF_FFFF_FFFF)
|
||||
}
|
||||
|
||||
/// Id of the i-th Excel 2010 conditional format rule of the package (deterministic and unique,
|
||||
/// like [`person_guid`]).
|
||||
pub fn x14_cf_rule_guid(i: u32) -> String {
|
||||
format!("{{00000000-0000-4000-8003-{i:012X}}}")
|
||||
}
|
||||
|
||||
/// `$A$1:$D$20` (or `$1:$3` / `$A:$C`).
|
||||
pub fn abs_range(r: &RangeRef) -> String {
|
||||
let c = |col: u32| gridcraft_core::col_to_letters(col);
|
||||
@@ -264,6 +274,8 @@ pub fn write_xlsx_named_with(wb: &Workbook, kind: XlsxKind, book_name: Option<&s
|
||||
overrides: vec![],
|
||||
defaults: BTreeMap::new(),
|
||||
dxfs: vec![],
|
||||
num_fmts: Default::default(),
|
||||
x14_cf_rules: 0,
|
||||
sst: Sst::default(),
|
||||
images: 0,
|
||||
media: HashMap::new(),
|
||||
@@ -367,7 +379,7 @@ pub fn write_xlsx_named_with(wb: &Workbook, kind: XlsxKind, book_name: Option<&s
|
||||
w.push_str("</workbook>");
|
||||
|
||||
// Workbook-level parts.
|
||||
let (styles, fmt_ids) = crate::styles::write_styles(wb, &out.dxfs, &pivots.number_formats(wb));
|
||||
let (styles, fmt_ids) = crate::styles::write_styles(wb, &out.dxfs, &pivots.number_formats(wb), std::mem::take(&mut out.num_fmts));
|
||||
pivots.finish(wb, &mut out, &|code: &str| crate::tables::builtin_id(code).or_else(|| fmt_ids.get(code).copied()));
|
||||
out.part("xl/styles.xml", Some("application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"), styles.into_bytes());
|
||||
wb_rels.add("styles", "styles.xml");
|
||||
|
||||
@@ -80,7 +80,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real
|
||||
|
||||
| Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests |
|
||||
|---|---|---|---|---|---|
|
||||
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), form controls (buttons, scroll bars and spin buttons: control properties parts, `<controls>` and VML `x:ClientData`; a VML-only control is read too; a button's command, fixed input range or output cell travels in a hidden defined name and comes back only onto the same button while the file still assigns its macro, or none for a command), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), other form controls (check boxes, list boxes, drop-downs; written in the same `<controls>` element and VML drawing as the modelled ones, also those only the VML drawing lists, with no `<controls>` entry), ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
|
||||
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF (including the Excel 2010 `x14:conditionalFormattings` extension, MS-XLSX 2.4.6: `cellIs`, `expression`, `containsBlanks`/`notContainsBlanks`, `containsErrors`/`notContainsErrors`, `duplicateValues`/`uniqueValues`, `top10`, `aboveAverage` and `timePeriod` rules are read, with `xm:f` formulas and an inline `x14:dxf`; x14 data bars (beyond the solid fill a main-section data bar links to), icon sets, colour scales and the text rules `containsText`, `notContainsText`, `beginsWith` and `endsWith` are skipped with a warning and lost on save. Cell-value and formula rules referring to another sheet are written in the extension using `{78C0D931-6437-407d-A8EE-F0AAD7539E65}`; in the tested synthetic files, Excel for Mac 16.114 also wrote cross-sheet `expression` rules there and opened them without a repair prompt. Excel for Mac 16.114 stores cross-sheet `cfvo` rules for colour scales, data bars and icon sets only in x14; GridCraft writes those rules in the main section, and drops x14-only rules of those kinds on read with a warning. A rule with a 3-D span stays in the main section, since MS-XLSX 2.6.27 forbids `sheet-range-reference` in `xm:f`. Colour scale, data bar and icon set rules (whose cfvo formulas can also refer to other sheets) are always written in the main section), validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), form controls (buttons, scroll bars and spin buttons: control properties parts, `<controls>` and VML `x:ClientData`; a VML-only control is read too; a button's command, fixed input range or output cell travels in a hidden defined name and comes back only onto the same button while the file still assigns its macro, or none for a command), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), other form controls (check boxes, list boxes, drop-downs; written in the same `<controls>` element and VML drawing as the modelled ones, also those only the VML drawing lists, with no `<controls>` entry), ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
|
||||
| `.xlsx` Legacy formula behavior | R/W | yes | yes | Formulas without dynamic-array metadata (`cm`) open with Excel's implicit `@`; implied operators are removed on save without `cm`, while explicit single-value `@` is kept as `_xlfn.SINGLE`; formulas the analyzer cannot finish are saved as read. | `roundtrip.rs`, `fixtures.rs` |
|
||||
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
|
||||
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
|
||||
@@ -221,6 +221,8 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
|
||||
| 2026-10-14 | minor | PDF export writes clickable annotations for safe cell URLs and destinations on printed pages; CLI `convert` accepts `.pdf` output (#954) |
|
||||
| 2026-10-13 | minor | Legacy vs dynamic-array formulas: no `cm` reads as legacy (implicit `@` inserted), implied `@` written back without `cm` |
|
||||
| 2026-10-13 | trivial | XLSX export keeps a picture shared by several sheets as one media part (#985) |
|
||||
| 2026-10-14 | trivial | Formula parser: text longer than Excel's 8,192 characters, and postfix chains (`1%%%…`, `f(1)(1)…`) past the 256-level nesting limit, are parse errors (the cell keeps its formula text and cached value) instead of trees deep enough to overflow the stack when a hostile file is opened, saved or dropped |
|
||||
| 2026-10-13 | minor | XLSX: Excel 2010 conditional formats (`x14:conditionalFormattings`) are read (`cellIs`, `expression`, blanks, errors, duplicate/unique, top 10, above average and time period rules with inline `x14:dxf`, priorities merged with the main section; data bars beyond a main-section bar's solid fill, icon sets, colour scales and the four text rules are still skipped with a warning) and cell-value and formula rules referring to another sheet (not a 3-D span) are written back in that extension, following a LibreOffice-saved file; Excel for Mac 16.114 puts cross-sheet formula (`expression`) rules there too (synthetic files; GridCraft's open with no repair prompt). Colour scale, data bar and icon set cfvo formulas referring to another sheet stay in the main section: Excel 16.114 keeps them only in x14, and opens GridCraft's main-section ones without a repair prompt. Before, these rules were skipped with a warning |
|
||||
| 2026-10-12 | trivial | XLSX chart sheets are kept on save (#727) |
|
||||
| 2026-10-12 | trivial | CSV and TSV export is capped at 512 MiB and refuses a larger used range with an error (#528) |
|
||||
| 2026-10-12 | minor | `.xls` import reads the calculation settings (CalcMode, CalcIter, CalcCount, CalcDelta, CalcPrecision), so circular models calculate instead of showing `#CIRC!` (#724) |
|
||||
|
||||
@@ -111,7 +111,10 @@ assertions each, but there is no conformance suite against Excel-computed result
|
||||
reports keep finding edge cases: MIN() with no arguments (#138), COUNTBLANK past the used range
|
||||
(#137, and past 16,384 cells #1010, fixed 10-14 for bounded references), ROUND at 15 digits and DATE(1900,2,29) (fixed 10-09), SUMIF sum-range sizing (fixed
|
||||
10-09). Statistical distributions and financial functions with iterative solvers (RATE, IRR,
|
||||
XIRR, YIELD) are the highest-risk for last-digit differences.
|
||||
XIRR, YIELD) are the highest-risk for last-digit differences. RATE follows Excel's own iteration, reconstructed from observation (secant from the guess and the guess ± 0.001, at most 200 steps,
|
||||
stop within 1e-7 by step and value, a looser 1e-4 check after 200 steps), so it returns the same
|
||||
iterate as Excel where convergence is slow (about -100% for `RATE(n,0,-pv,0)`) and `#NUM!` where
|
||||
Excel's solver gives up (very large rates); roots at 0% differ only by rounding noise (under 1e-7).
|
||||
|
||||
TEXT() and cell display share `crates/numfmt`; checked against Excel-cached results in
|
||||
number- and text-format test workbooks (352 TEXT cells), all match:
|
||||
@@ -178,6 +181,7 @@ Positive fractional inputs still truncate, and signed zero remains valid. Covere
|
||||
| 2026-10-14 | minor | Set precision as displayed: results, spills and typed or reformatted numbers are stored as their format shows them when the option is on (#1343) |
|
||||
| 2026-10-14 | minor | Number-to-text (`&`, CONCAT, TEXTJOIN, VALUETOTEXT, the IM functions' complex text, and also formula printing, pivot and chart labels) rounds to 15 significant digits before choosing decimal or scientific, so `=(1E15-0.5)&""` is `1E+15`, not `1000000000000000`; and below 1 it switches to scientific when the decimal would be longer than 21 characters (sign not counted), as Excel caches IMCSCH/IMEXP/IMTAN results: `1.28233995888454E-06`, so `9.99999999999999E-09` (was `0.00000001`), but `0.0000692361330972509`. Only 15-digit positive mantissas are Excel-verified; the limit for shorter mantissas and for negatives is inferred |
|
||||
| 2026-10-14 | minor | Bounded references up to 1,048,576 cells (`D3:AZ400`) keep their full shape instead of stopping at the used range, so `SUMPRODUCT(D3:AZ400*B3:B400,(A3:A400=x)*(D1:AZ1=y))` broadcasts like Excel and `ROWS`, `COUNTBLANK` and `--(r="")` count the blanks; references that run to the edge of the sheet (`A:A`) still stop at the used range (#1010) |
|
||||
| 2026-10-14 | minor | RATE follows Excel's iteration (secant, 200 steps, 1e-7 by step and value): `RATE(5,0,-100,0)` is -0.999999409145182 like Excel instead of `#NUM!`, `RATE(4,0,-0.0001,100)` is `#NUM!` like Excel instead of 30.62 |
|
||||
| 2026-10-13 | minor | Legacy formulas from files (no dynamic-array metadata) evaluate with implicit intersection: cells differing from Excel's cached values 68,964 → 49,866 across 4,224 test-corpus workbooks (none gets more) |
|
||||
| 2026-10-13 | minor | Clear reports changed stored cells sparsely, including those beyond the first million coordinates; dependent formulas and removed spills update, while clearing empty merges still unblocks spills (#1032) |
|
||||
| 2026-10-12 | minor | GETPIVOTDATA added: 514 / 523 by name, 505 working |
|
||||
|
||||
+10
-3
@@ -35,9 +35,15 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
|
||||
|
||||
### 3. Some unmodelled XLSX content is dropped on save (FF)
|
||||
- **Missing:** slicers and their caches, timelines, the data model, query tables attached to
|
||||
tables, unmodelled `extLst` entries, chart details. Pass-through (#330) keeps custom XML,
|
||||
external links, connections, sheet query tables, printer settings, form and ActiveX controls,
|
||||
OLE objects and sheet backgrounds; never checked in Excel (repair prompts unknown).
|
||||
tables, unmodelled `extLst` entries (among them x14 data bar settings beyond a solid fill,
|
||||
icon sets, colour scales and the text rules containsText, notContainsText, beginsWith and
|
||||
endsWith), chart details. Pass-through (#330) keeps custom XML, external links, connections,
|
||||
sheet query tables, printer settings, form and ActiveX controls, OLE objects and sheet
|
||||
backgrounds; x14-only colour-scale, data-bar and icon-set rules with cross-sheet `cfvo` are
|
||||
still dropped on read with a warning, while the other Excel 2010 conditional format rules
|
||||
(including cross-sheet cell-value and expression rules) are read and written. In tested
|
||||
synthetic files, Excel for Mac 16.114 stored cross-sheet expression and `cfvo` rules in x14;
|
||||
GridCraft-written main-section cfvo files opened without a repair prompt.
|
||||
- **Evidence:** `crates/xlsx/src/passthrough.rs` (what is kept, and why the rest isn't).
|
||||
- **Impact:** open-edit-save still simplifies workbooks with slicers, timelines or Power Pivot.
|
||||
- **Estimate:** 6–10 h. [file-format-parity.md](file-format-parity.md)
|
||||
@@ -207,6 +213,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
|
||||
| 2026-10-17 | minor | §6: the five reports it tracked are closed and their PRs merged (#57, #133, #139, #140, #134; PRs #148, #155, #156, #157); the entry stays open for §15's oracle suite |
|
||||
| 2026-10-15 | minor | §6: Maximum Iterations and Maximum Change in File › Options › Formulas; dropped the stale "no Options dialog yet" |
|
||||
| 2026-10-15 | minor | §13: Solver prepares reports before committing the solution, model and report sheets together; report refusal preserves the workbook and Undo/Redo (#1050) |
|
||||
| 2026-10-13 | minor | §3: Excel 2010 conditional formats (`x14:conditionalFormattings`, cross-sheet rules) read, evaluated and written back in the extension |
|
||||
| 2026-10-13 | trivial | §4: multi-level category axes landed |
|
||||
| 2026-10-12 | minor | §9: next/previous sheet commands retain the current visible sheet and selection when there is no visible destination |
|
||||
| 2026-10-12 | minor | §8, §15: GETPIVOTDATA added (9 functions missing) |
|
||||
|
||||
Reference in new issue
Block a user