XLSX: read, evaluate and write Excel 2010 conditional formats (#717)

XLSX: read, evaluate and write Excel 2010 conditional formats

Excel 2010+ keeps conditional format rules whose formulas refer to
other sheets only in the worksheet's x14:conditionalFormattings
extension, with xm:f formulas and an inline x14:dxf in place of a
dxfId. GridCraft skipped the whole extension with a warning.

Read: x14 cellIs (every operator, one or two formulas), expression,
blanks, errors, duplicate/unique, top 10, above average and time
period rules become ordinary rules, with the inline differential
format (font, fill, border, number format) and priorities that
interleave with the main section's. A data bar's linked extension
(the x14:id of a main-section rule) adds no second rule. Other x14
kinds (data bar settings, x14 icon sets) are skipped with a warning
naming the kind.

Evaluate: cross-sheet references in rule formulas already resolve;
an engine test pins cellIs and expression rules against cells on
another sheet.

Write: a cell-value or formula rule referring to another sheet is
written in the x14 extension ({78C0D931-6437-407d-A8EE-F0AAD7539E65})
with an inline x14:dxf and a unique id; other rules stay in the main
section. The extension shares one extLst with the sparklines (CF
first). Inline number formats get ids styles.xml declares.

XLSX: say which x14 conditional format rules stay in the main section

Colour scale, data bar and icon set rules are always written in the main
section, even when their cfvo formulas refer to other sheets; the parity
docs now say so. (This commit first dropped the
reader's own x14:id linking; after the rebase onto main, main's data bar
linking from #550 is the one path, so only the docs part remains.)
XLSX: correct the x14 conditional format provenance and list skipped kinds

The file that motivated the x14 conditional format work
(watchdog-report.xlsx) was saved by LibreOffice 25.2, not Excel, so
nothing observed in Excel backs the earlier commit's statement that
Excel 2010+ keeps cross-sheet rules only in the extension. MS-XLSX
2.6.27 (CT_CfRule) allows single-sheet references in xm:f but says
nothing about where Excel places such rules; the comments and docs now
say the placement follows the LibreOffice-saved file and Excel's own
is unverified.

MS-XLSX 2.6.27 forbids sheet-range-reference (3-D spans) in xm:f, so a
rule with a 3-D span now stays in the main section.

The parity docs and gaps list name the x14 kinds read (cellIs,
expression, blanks, errors, duplicate/unique, top10, aboveAverage,
timePeriod) and those skipped with a warning and lost on save (data
bars, icon sets, colour scales, containsText, notContainsText,
beginsWith, endsWith).

Styles: differential formats keep their cell protection on save

dxf_xml, which writes both styles.xml dxfs and inline x14:dxf elements, wrote font, number format, fill, alignment and border but never protection, although read_dxf reads it. A rule whose format unlocked or hid cells lost that on save. It now writes protection after border, the order CT_Dxf requires.
XLSX: solid data bars are saved with negatives in the bar colour and no axis, as GridCraft draws them
docs: order parity revision history
docs: record verified x14 conditional format placement
docs: fold the Excel check into the PR's own changelog row instead of a new dated row
docs: the Excel check covered cross-sheet expression rules, not cell-value rules
Fix differential format serialization
Preserve default dxf protection
This commit is contained in:
neilcawse authored and GitHub committed 2026-11-18 21:13:46 +07:00
1 parent aef4ceb10d
commit f8af138f28
10 files changed
+511 -173

No files matched your search

+37
View File
@@ -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();
+5 -21
View File
@@ -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),
_ => {}
}
}
+150 -65
View File
@@ -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),
});
}
}
+40 -36
View File
@@ -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> {
+54
View File
@@ -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
View File
@@ -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
+138
View File
@@ -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&gt;Sheet1!$B$1</formula>"), "{main}");
assert!(main.contains("<formula>SUM('Sheet1:Vehicle Range'!$A$1)&gt;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];
+13 -1
View File
@@ -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");
+3 -1
View File
@@ -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) |
+10 -3
View File
@@ -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) |