xlsx: delegate worksheet, drawing, and chart XML to craft-xlsx (storytold/craft-libs#778) (#4562)

* xlsx: delegate worksheet, drawing, and chart XML to craft-xlsx (storytold/craft-libs#778)

* xlsx: fix craft-libs type mismatches for CI gate

* fix(xlsx): borrow CANONICAL in drawing::Options::canonical

* xlsx: bump craft-libs to ed3aad7c3, sync Cargo.lock, and add #778 round-trip test

* xlsx: remove dead RowState fields and gate test-only push_a1

* xlsx: preserve per-series box-whisker quartileMethod and pin craft-libs main

* xlsx: read chartex series formulas and tx refs from chartData

* xlsx: handle chartex XML without chartData in read_chartex

* xlsx: honour omitted val attribute on <c:smooth/>

* xlsx: include series-level data_labels in Chart::data_labels

* xlsx: accept self-closing <a:rPr/> in equation_tests

* xlsx: detect secondary axis on combo groups with unreferenced axId

* fix(xlsx): replace ax_ids closure with fn to satisfy lifetime inference

* xlsx: fix clippy needless_lifetimes warning in chart.rs

* xlsx: preserve LineMarkers default and validation order before extLst

* xlsx: preserve same-type multi-axis charts, skip damaged note VML, and report oversized sheet XML as damaged

* xlsx: keep part-size TooLarge errors as IoError::TooLarge

* xlsx: read multiple hyperlinks blocks and cap merges at MAX_XML_NODES

* xlsx: use sheet_part.merges for MAX_XML_NODES check

* xlsx: read multiple cols blocks when present

* xlsx: keep SHEET_SLOTS order for AlternateContent oleObjects before controls

* xlsx: fall back to marker spPr solidFill for scatter series color

* xlsx: read chartex axis titles from cx:axis/cx:title

* xlsx: read chartex series color from cx:spPr/a:solidFill

* xlsx: read trendline CT_Boolean defaults and large forecast values from XML
This commit is contained in:
Dylan M. Taylor
2026-11-20 06:21:14 -05:00
committed by GitHub
parent 865f3e3f18
commit 4aab8a7026
13 changed files with 1721 additions and 1547 deletions
Generated
+17 -59
View File
@@ -940,20 +940,9 @@ dependencies = [
[[package]]
name = "craft-drawingml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
source = "git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0#0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
"kurbo",
"log",
"serde",
]
[[package]]
name = "craft-drawingml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288#512a1b8e8b59a7b325e7f69f6131aa8628470288"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0)",
"kurbo",
"log",
"serde",
@@ -1063,21 +1052,10 @@ dependencies = [
[[package]]
name = "craft-opc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288#512a1b8e8b59a7b325e7f69f6131aa8628470288"
source = "git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0#0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)",
"log",
"thiserror 2.0.21",
]
[[package]]
name = "craft-opc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0)",
"log",
"thiserror 2.0.21",
]
@@ -1109,12 +1087,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c85293
[[package]]
name = "craft-sheet"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
source = "git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0#0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0"
[[package]]
name = "craft-sheet"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288#512a1b8e8b59a7b325e7f69f6131aa8628470288"
source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
[[package]]
name = "craft-stream-codecs"
@@ -1229,12 +1207,12 @@ dependencies = [
[[package]]
name = "craft-xlsx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288#512a1b8e8b59a7b325e7f69f6131aa8628470288"
source = "git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0#0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0"
dependencies = [
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)",
"craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)",
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)",
"craft-drawingml",
"craft-opc",
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0)",
"thiserror 2.0.21",
]
@@ -1251,17 +1229,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288#512a1b8e8b59a7b325e7f69f6131aa8628470288"
source = "git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0#0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -1290,17 +1258,7 @@ dependencies = [
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288#512a1b8e8b59a7b325e7f69f6131aa8628470288"
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip 9.1.0",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
source = "git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0#0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -2539,14 +2497,14 @@ version = "0.19.1"
dependencies = [
"craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"craft-csv",
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
"craft-drawingml",
"craft-math",
"craft-ods",
"craft-offcrypto",
"craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"craft-opc",
"craft-xls",
"craft-xlsx",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0)",
"gridcraft-core",
"gridcraft-formula",
"gridcraft-functions",
+5 -5
View File
@@ -39,7 +39,7 @@ craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
# OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`.
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0", version = "0.1.0" }
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
# turn them into workbooks.
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
@@ -47,11 +47,11 @@ craft-math = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" }
# Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model.
# SpreadsheetML string encoding/decoding and XLSB package/record parsing; workbook model mapping stays in gridcraft-xlsx.
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "512a1b8e8b59a7b325e7f69f6131aa8628470288", version = "0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
# SpreadsheetML worksheet/drawing/string/package XML; workbook model mapping stays in gridcraft-xlsx.
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0", version = "0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0", version = "0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e", version = "0.1.0" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e", version = "0.1.0" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0", version = "0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c", version = "=0.1.0" }
# foundation
+225 -204
View File
@@ -3,64 +3,143 @@
use std::fmt::Write as _;
use craft_drawingml::chart::{Chart as DmlChart, ChartType, Trendline as DmlTrendline, TrendlineType};
use craft_drawingml::color::SchemeSlot;
use craft_drawingml::style::{ColorBase, ColorRef as DmlColor, Fill as DmlFill};
use gridcraft_core::{RangeRef, Value, category_levels};
use gridcraft_formula::{Expr, SheetSel};
use gridcraft_model::{Chart, ChartKind, Color, DefinedName, LegendPos, LineDash, Series, Trendline, TrendlineKind, Workbook};
use gridcraft_model::{Chart, ChartDataTable, ChartKind, Color, DefinedName, LegendPos, LineDash, Series, Trendline, TrendlineKind, Workbook};
use crate::drawing::{dml_color, srgb};
use crate::xml::{El, esc, num};
// ---------------------------------------------------------------- reading
fn group_kind(g: &El) -> Option<ChartKind> {
let grouping = g.child_val("grouping").unwrap_or("standard");
let stacked = grouping == "stacked";
let pct = grouping == "percentStacked";
Some(match g.name.as_str() {
"barChart" | "bar3DChart" => {
let bar = g.child_val("barDir") == Some("bar");
match (bar, stacked, pct) {
(false, true, _) => ChartKind::ColumnStacked,
(false, _, true) => ChartKind::ColumnStacked100,
(false, _, _) => ChartKind::ColumnClustered,
(true, true, _) => ChartKind::BarStacked,
(true, _, true) => ChartKind::BarStacked100,
(true, _, _) => ChartKind::BarClustered,
}
pub(crate) fn to_craft_el(e: &El) -> craft_xml::El {
let mut out = craft_xml::El::new(e.name.as_str());
out.attrs = e.attrs.clone();
for c in &e.children {
out.children.push(craft_xml::Node::El(to_craft_el(c)));
}
if !e.text.is_empty() {
out.children.push(craft_xml::Node::Text(e.text.clone()));
}
out
}
pub(crate) fn map_dml_color(c: &DmlColor) -> Option<Color> {
match &c.base {
ColorBase::Rgb { rgb } => Some(Color::Rgb((u32::from(rgb.r) << 16) | (u32::from(rgb.g) << 8) | u32::from(rgb.b))),
ColorBase::Scheme { slot } => {
let i = match slot {
SchemeSlot::Bg1 | SchemeSlot::Lt1 => 0,
SchemeSlot::Tx1 | SchemeSlot::Dk1 => 1,
SchemeSlot::Bg2 | SchemeSlot::Lt2 => 2,
SchemeSlot::Tx2 | SchemeSlot::Dk2 => 3,
SchemeSlot::Accent1 => 4,
SchemeSlot::Accent2 => 5,
SchemeSlot::Accent3 => 6,
SchemeSlot::Accent4 => 7,
SchemeSlot::Accent5 => 8,
SchemeSlot::Accent6 => 9,
SchemeSlot::Hlink => 10,
SchemeSlot::FolHlink => 11,
SchemeSlot::PhClr => return None,
};
Some(Color::Theme(i, 0))
}
"lineChart" | "line3DChart" => {
if stacked || pct {
ChartKind::LineStacked
} else {
let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true");
let all_none = g.kids("ser").all(|s| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"));
if !group_markers || (all_none && g.kids("ser").next().is_some()) { ChartKind::Line } else { ChartKind::LineMarkers }
}
ColorBase::System { last, .. } => Some(Color::Rgb((u32::from(last.r) << 16) | (u32::from(last.g) << 8) | u32::from(last.b))),
ColorBase::Preset { .. } => None,
}
}
fn map_chart_type(k: ChartType, plot: Option<&El>) -> ChartKind {
match k {
ChartType::Column => ChartKind::ColumnClustered,
ChartType::StackedColumn => ChartKind::ColumnStacked,
ChartType::PercentColumn => ChartKind::ColumnStacked100,
ChartType::Bar => ChartKind::BarClustered,
ChartType::StackedBar => ChartKind::BarStacked,
ChartType::PercentBar => ChartKind::BarStacked100,
ChartType::Line => {
let markers = plot
.into_iter()
.flat_map(|p| p.kids("lineChart").chain(p.kids("line3DChart")))
.filter(|g| !matches!(g.child_val("grouping"), Some("stacked" | "percentStacked")))
.any(|g| {
let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true");
let all_none = g.kids("ser").all(|s| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"));
group_markers && !(all_none && g.kids("ser").next().is_some())
});
if markers { ChartKind::LineMarkers } else { ChartKind::Line }
}
"pieChart" | "pie3DChart" | "ofPieChart" => ChartKind::Pie,
"doughnutChart" => ChartKind::Doughnut,
"areaChart" | "area3DChart" => {
if pct {
ChartKind::AreaStacked100
} else if stacked {
ChartKind::AreaStacked
} else {
ChartKind::Area
}
ChartType::LineMarkers => ChartKind::LineMarkers,
ChartType::StackedLine => ChartKind::LineStacked,
ChartType::Area => ChartKind::Area,
ChartType::StackedArea => {
let pct = plot
.into_iter()
.flat_map(|p| p.kids("areaChart").chain(p.kids("area3DChart")))
.any(|g| g.child_val("grouping") == Some("percentStacked"));
if pct { ChartKind::AreaStacked100 } else { ChartKind::AreaStacked }
}
"scatterChart" => {
let no_lines = g.kids("ser").all(|s| s.path(&["spPr", "ln"]).is_some_and(|l| l.child("noFill").is_some()));
if g.child_val("scatterStyle") == Some("marker") || (no_lines && g.kids("ser").next().is_some()) {
ChartKind::Scatter
} else {
ChartKind::ScatterLines
}
ChartType::Pie => ChartKind::Pie,
ChartType::Doughnut => ChartKind::Doughnut,
ChartType::Scatter => {
let marker_only = plot.and_then(|p| p.child("scatterChart")).is_some_and(|g| {
let no_lines = g.kids("ser").all(|s| s.path(&["spPr", "ln"]).is_some_and(|l| l.child("noFill").is_some()));
g.child_val("scatterStyle") == Some("marker") || (no_lines && g.kids("ser").next().is_some())
});
if marker_only { ChartKind::Scatter } else { ChartKind::ScatterLines }
}
"bubbleChart" => ChartKind::Bubble,
"radarChart" => ChartKind::Radar,
"stockChart" => ChartKind::Stock,
_ => return None,
})
ChartType::Bubble => ChartKind::Bubble,
ChartType::Radar | ChartType::FilledRadar => ChartKind::Radar,
ChartType::Stock => ChartKind::Stock,
ChartType::Combo => ChartKind::Combo,
_ => ChartKind::ColumnClustered,
}
}
fn map_trendline(t: &DmlTrendline, el: Option<&El>) -> Trendline {
let kind = match t.kind {
TrendlineType::Linear => TrendlineKind::Linear,
TrendlineType::Exp => TrendlineKind::Exponential,
TrendlineType::Log => TrendlineKind::Logarithmic,
TrendlineType::Power => TrendlineKind::Power,
TrendlineType::Poly => TrendlineKind::Polynomial(t.order.unwrap_or(2).clamp(2, 6) as u8),
TrendlineType::MovingAvg => TrendlineKind::MovingAverage(t.period.unwrap_or(2).clamp(2, 255)),
};
let ln = el.and_then(|e| e.path(&["spPr", "ln"]));
let forecast = |name: &str, dml: Option<f64>| {
Trendline::clamp_forecast(el.and_then(|e| e.child(name)).and_then(|c| c.attr_f64("val")).or(dml).unwrap_or(0.0))
};
Trendline {
kind,
name: t.name.clone(),
forward: forecast("forward", t.forward),
backward: forecast("backward", t.backward),
intercept: t.intercept,
display_equation: el.and_then(|e| e.child("dispEq")).map_or(t.disp_eq, |c| c.flag("val", true)),
display_r_squared: el.and_then(|e| e.child("dispRSqr")).map_or(t.disp_r_sqr, |c| c.flag("val", true)),
color: ln.and_then(|l| l.child("solidFill")).and_then(dml_color),
width: ln.and_then(|l| l.attr_f64("w")).map(|w| (w / EMU_PER_PT) as f32).filter(|w| w.is_finite() && *w >= 0.0),
dash: ln.and_then(|l| l.child("prstDash")).and_then(|d| d.attr("val")).and_then(|v| DASHES.iter().find(|(_, n)| *n == v).map(|(d, _)| *d)),
}
}
fn literal_array(e: Option<&El>) -> Option<String> {
let e = e?;
for k in ["numLit", "strLit"] {
if let Some(l) = e.child(k) {
let pts: Vec<String> = l
.kids("pt")
.filter_map(|p| p.child("v"))
.map(|v| if k == "numLit" { v.text.trim().to_string() } else { format!("\"{}\"", v.text.replace('"', "\"\"")) })
.collect();
return Some(format!("{{{}}}", pts.join(",")));
}
}
None
}
/// Excel's file notation for "this workbook" in front of a workbook-scoped defined name.
@@ -101,51 +180,6 @@ pub(crate) fn chart_ref_from_file(text: &str) -> String {
out
}
fn data_ref(e: Option<&El>) -> Option<String> {
let e = e?;
for k in ["numRef", "strRef", "multiLvlStrRef"] {
if let Some(f) = e.child(k).and_then(|r| r.child("f")) {
return Some(chart_ref_from_file(&f.text));
}
}
// Literal values become an array constant.
for k in ["numLit", "strLit"] {
if let Some(l) = e.child(k) {
let pts: Vec<String> = l
.kids("pt")
.filter_map(|p| p.child("v"))
.map(|v| if k == "numLit" { v.text.trim().to_string() } else { format!("\"{}\"", v.text.replace('"', "\"\"")) })
.collect();
return Some(format!("{{{}}}", pts.join(",")));
}
}
None
}
fn read_series(s: &El) -> Series {
let name = s
.child("tx")
.and_then(|tx| tx.path(&["strRef", "f"]).map(|f| chart_ref_from_file(&f.text)).or_else(|| tx.child("v").map(|v| v.text.clone())));
let sp = s.child("spPr");
let color = sp
.and_then(|p| p.child("solidFill"))
.and_then(dml_color)
.or_else(|| sp.and_then(|p| p.path(&["ln", "solidFill"])).and_then(dml_color))
.or_else(|| s.path(&["marker", "spPr", "solidFill"]).and_then(dml_color));
Series {
name,
categories: data_ref(s.child("cat")).or_else(|| data_ref(s.child("xVal"))),
values: data_ref(s.child("val")).or_else(|| data_ref(s.child("yVal"))).unwrap_or_default(),
bubble_sizes: data_ref(s.child("bubbleSize")),
color,
secondary: false,
kind: None,
quartiles: Default::default(),
smooth: bool_val(s, "smooth"),
trendlines: s.kids("trendline").filter_map(read_trendline).collect(),
}
}
const DASHES: [(LineDash, &str); 11] = [
(LineDash::Solid, "solid"),
(LineDash::Dot, "dot"),
@@ -162,132 +196,119 @@ const DASHES: [(LineDash, &str); 11] = [
const EMU_PER_PT: f64 = 12_700.0;
/// A `CT_Boolean` child (`val` defaults to true).
fn bool_val(e: &El, tag: &str) -> bool {
e.child(tag).is_some_and(|c| c.flag("val", true))
}
fn f64_val(e: &El, tag: &str) -> Option<f64> {
e.child(tag).and_then(|c| c.attr_f64("val"))
}
/// `<c:trendline>` (ECMA-376 Part 1, 21.2.2.211). Unknown types are dropped.
fn read_trendline(t: &El) -> Option<Trendline> {
let kind = match t.child_val("trendlineType").unwrap_or("linear") {
"linear" => TrendlineKind::Linear,
"exp" => TrendlineKind::Exponential,
"log" => TrendlineKind::Logarithmic,
"power" => TrendlineKind::Power,
"poly" => TrendlineKind::Polynomial(t.child_val("order").and_then(|v| v.trim().parse::<u8>().ok()).unwrap_or(2).clamp(2, 6)),
"movingAvg" => TrendlineKind::MovingAverage(t.child_val("period").and_then(|v| v.trim().parse::<u32>().ok()).unwrap_or(2).clamp(2, 255)),
_ => return None,
};
let ln = t.path(&["spPr", "ln"]);
Some(Trendline {
kind,
name: t.child("name").map(|n| n.text.clone()),
forward: Trendline::clamp_forecast(f64_val(t, "forward").unwrap_or(0.0)),
backward: Trendline::clamp_forecast(f64_val(t, "backward").unwrap_or(0.0)),
intercept: f64_val(t, "intercept"),
display_equation: bool_val(t, "dispEq"),
display_r_squared: bool_val(t, "dispRSqr"),
color: ln.and_then(|l| l.child("solidFill")).and_then(dml_color),
width: ln.and_then(|l| l.attr_f64("w")).map(|w| (w / EMU_PER_PT) as f32).filter(|w| w.is_finite() && *w >= 0.0),
dash: ln.and_then(|l| l.child("prstDash")).and_then(|d| d.attr("val")).and_then(|v| DASHES.iter().find(|(_, n)| *n == v).map(|(d, _)| *d)),
})
}
fn rich_title(t: &El) -> Option<String> {
let tx = t.child("tx")?;
if let Some(rich) = tx.child("rich") {
let paras: Vec<String> =
rich.kids("p").map(|p| p.kids("r").filter_map(|r| r.child("t")).map(|t| t.text.as_str()).collect::<String>()).collect();
let s = paras.join("\n");
return if s.is_empty() { None } else { Some(s) };
pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart {
let plot = root.and_then(|r| r.path(&["chart", "plotArea"]));
let groups: Vec<&El> = plot.map(|p| p.children.iter().filter(|g| g.name.ends_with("Chart")).collect()).unwrap_or_default();
fn ax_ids(g: &El) -> Vec<&str> {
g.kids("axId").filter_map(|a| a.attr("val")).collect()
}
if let Some(sr) = tx.child("strRef") {
if let Some(v) = sr.path(&["strCache", "pt", "v"]) {
return Some(v.text.clone());
}
return sr.child("f").map(|f| f.text.trim().to_string());
}
None
}
fn axis_ids(g: &El) -> Vec<String> {
g.kids("axId").filter_map(|a| a.attr("val")).map(str::to_string).collect()
}
pub fn read_chart(root: &El) -> Option<Chart> {
let chart = root.child("chart")?;
let plot = chart.child("plotArea")?;
let groups: Vec<(&El, ChartKind)> = plot.children.iter().filter_map(|g| group_kind(g).map(|k| (g, k))).collect();
let (first, first_kind) = *groups.first()?;
let first_axes = axis_ids(first);
let mut series = vec![];
for (gi, (g, k)) in groups.iter().enumerate() {
for s in g.kids("ser") {
let mut ser = read_series(s);
if groups.len() > 1 {
// Every series of a combo chart keeps its own group's kind, the first group's included.
ser.kind = Some(*k);
let first_axes = groups.first().map(|g| ax_ids(g)).unwrap_or_default();
let ser_els: Vec<(&El, bool)> = groups
.iter()
.enumerate()
.flat_map(|(gi, g)| {
let sec = gi > 0 && ax_ids(g) != first_axes;
g.kids("ser").map(move |s| (s, sec))
})
.collect();
let multi_axis = ser_els.iter().any(|(_, sec)| *sec);
let is_combo = dc.kind == ChartType::Combo || multi_axis;
let base_kind = map_chart_type(dc.kind, plot);
let kind = if is_combo { ChartKind::Combo } else { base_kind };
let series_labels = dc.series.iter().any(|s| s.data_labels == Some(true));
let series = dc
.series
.into_iter()
.enumerate()
.map(|(i, s)| {
let (sel, fallback_sec) = match ser_els.get(i).copied() {
Some((el, sec)) => (Some(el), sec),
None => (None, false),
};
let color = s
.fill
.as_ref()
.and_then(|f| match f {
DmlFill::Solid { color } => map_dml_color(color),
_ => None,
})
.or_else(|| {
s.line.as_ref().and_then(|l| l.fill.as_ref()).and_then(|f| match f {
DmlFill::Solid { color } => map_dml_color(color),
_ => None,
})
})
.or_else(|| sel.and_then(|e| e.path(&["marker", "spPr", "solidFill"])).and_then(dml_color));
Series {
name: s.refs.name.as_deref().map(chart_ref_from_file).or_else(|| (!s.name.is_empty()).then_some(s.name)),
categories: s
.refs
.categories
.as_deref()
.map(chart_ref_from_file)
.or_else(|| literal_array(sel.and_then(|e| e.child("cat").or_else(|| e.child("xVal"))))),
values: s
.refs
.values
.as_deref()
.map(chart_ref_from_file)
.or_else(|| literal_array(sel.and_then(|e| e.child("val").or_else(|| e.child("yVal")))))
.unwrap_or_default(),
bubble_sizes: s.refs.sizes.as_deref().map(chart_ref_from_file).or_else(|| literal_array(sel.and_then(|e| e.child("bubbleSize")))),
color,
secondary: is_combo && (s.secondary_axis || fallback_sec),
kind: if dc.kind == ChartType::Combo {
s.kind.map(|k| map_chart_type(k, plot))
} else if multi_axis {
Some(s.kind.map(|k| map_chart_type(k, plot)).unwrap_or(base_kind))
} else {
None
},
quartiles: Default::default(),
smooth: sel.map_or(s.smooth, |e| e.child("smooth").is_some_and(|c| c.flag("val", true))),
trendlines: s.trendlines.iter().enumerate().map(|(ti, t)| map_trendline(t, sel.and_then(|e| e.kids("trendline").nth(ti)))).collect(),
}
if gi > 0 {
ser.secondary = axis_ids(g) != first_axes;
}
series.push(ser);
}
}
let kind = if groups.len() > 1 { ChartKind::Combo } else { first_kind };
let show_val = |e: &El| e.child("dLbls").is_some_and(|d| bool_val(d, "showVal"));
let data_labels = groups.iter().any(|(g, _)| show_val(g) || g.kids("ser").any(show_val));
let val_axes: Vec<&El> = plot.kids("valAx").collect();
let cat_ax = plot.child("catAx").or_else(|| plot.child("dateAx"));
let scatter = matches!(first_kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble);
let (x_ax, y_ax) = if scatter {
let x = val_axes.iter().find(|a| matches!(a.child_val("axPos"), Some("b") | Some("t"))).copied();
let y = val_axes.iter().find(|a| matches!(a.child_val("axPos"), Some("l") | Some("r"))).copied();
(x, y)
} else {
(cat_ax, val_axes.first().copied())
};
let legend = match chart.child("legend") {
})
.collect();
let legend = match dc.legend.as_deref() {
None => LegendPos::None,
Some(l) => match l.child_val("legendPos").unwrap_or("r") {
"b" => LegendPos::Bottom,
"t" => LegendPos::Top,
"l" => LegendPos::Left,
_ => LegendPos::Right,
},
Some("b") => LegendPos::Bottom,
Some("t") => LegendPos::Top,
Some("l") => LegendPos::Left,
Some(_) => LegendPos::Right,
};
let doughnut = plot.child("doughnutChart");
let hole_size = doughnut.and_then(|g| g.child_val("holeSize")).and_then(|v| v.trim().parse::<u8>().ok()).unwrap_or(75).clamp(10, 90);
let first_slice_angle =
plot.child("pieChart").or(doughnut).and_then(|g| g.child_val("firstSliceAng")).and_then(|v| v.trim().parse::<u16>().ok()).unwrap_or(0) % 360;
Some(Chart {
let hole_size =
if plot.is_some_and(|p| p.child("doughnutChart").is_some()) { (dc.hole_size * 100.0).round().clamp(10.0, 90.0) as u8 } else { 75 };
Chart {
id: 0,
kind,
anchor: Default::default(),
title: chart.child("title").and_then(rich_title),
title: dc.title,
series,
legend,
data_labels,
data_table: plot.child("dTable").map(|t| gridcraft_model::ChartDataTable {
show_keys: bool_val(t, "showKeys"),
horizontal_border: bool_val(t, "showHorzBorder"),
vertical_border: bool_val(t, "showVertBorder"),
outline: bool_val(t, "showOutline"),
data_labels: dc.data_labels || series_labels,
data_table: dc.data_table.map(|t| ChartDataTable {
show_keys: t.show_keys,
horizontal_border: t.horizontal_border,
vertical_border: t.vertical_border,
outline: t.outline,
}),
gridlines: val_axes.iter().any(|a| a.child("majorGridlines").is_some()),
style: root.child_val("style").and_then(|v| v.parse().ok()).unwrap_or(2),
gridlines: dc.gridlines,
style: dc.style,
hole_size,
first_slice_angle,
x_title: x_ax.and_then(|a| a.child("title")).and_then(rich_title),
y_title: y_ax.and_then(|a| a.child("title")).and_then(rich_title),
first_slice_angle: dc.first_slice_angle,
x_title: dc.axis_titles.0,
y_title: dc.axis_titles.1,
source: None,
by_rows: false,
pivot: root.path(&["pivotSource", "name"]).map(|n| strip_book(n.text.trim()).to_string()).filter(|n| !n.is_empty()),
})
pivot: dc.pivot_source.as_deref().map(strip_book).filter(|n| !n.is_empty()).map(str::to_string),
}
}
pub fn read_chart(root: &El) -> Option<Chart> {
let craft = to_craft_el(root);
let dc = craft_drawingml::chart::read::chart_from(&craft)?;
Some(from_dml_chart(dc, Some(root)))
}
// ---------------------------------------------------------------- writing
+94 -67
View File
@@ -8,7 +8,7 @@ use gridcraft_core::RangeRef;
use gridcraft_formula::{Expr, SheetSel};
use gridcraft_model::{Chart, ChartKind, LegendPos, QuartileMethod, Series, Workbook};
use crate::drawing::{dml_color, srgb};
use crate::drawing::srgb;
use crate::xml::{El, esc, esc_attr};
pub const CT_CHARTEX: &str = "application/vnd.ms-office.chartex+xml";
@@ -43,24 +43,12 @@ pub fn requires(k: ChartKind) -> (&'static str, &'static str) {
// ---------------------------------------------------------------- reading
fn kind_of(layout: &str) -> Option<ChartKind> {
Some(match layout {
"clusteredColumn" | "paretoLine" => ChartKind::Histogram,
"boxWhisker" => ChartKind::BoxWhisker,
"waterfall" => ChartKind::Waterfall,
"funnel" => ChartKind::Funnel,
"treemap" => ChartKind::Treemap,
"sunburst" => ChartKind::Sunburst,
_ => return None,
})
}
fn formula(dim: &El) -> Option<String> {
fn chartex_formula(dim: &El) -> Option<String> {
let f = dim.child("f")?;
Some(crate::fmla::from_file(&crate::chart::chart_ref_from_file(&f.text)))
}
fn text(tx: &El) -> Option<String> {
fn chartex_text(tx: &El) -> Option<String> {
if let Some(d) = tx.child("txData") {
if let Some(f) = d.child("f") {
return Some(crate::chart::chart_ref_from_file(&f.text));
@@ -73,85 +61,124 @@ fn text(tx: &El) -> Option<String> {
if s.is_empty() { None } else { Some(s) }
}
pub fn read_chartex(root: &El) -> Option<Chart> {
let chart = root.child("chart")?;
let plot = chart.child("plotArea")?;
let region = plot.child("plotAreaRegion")?;
// Data by id: (categories, values).
pub(crate) fn from_dml_chartex(dc: craft_drawingml::chart::Chart, root: Option<&El>) -> Option<Chart> {
use craft_drawingml::chart::ChartType;
let kind = match dc.kind {
ChartType::Histogram | ChartType::Pareto => ChartKind::Histogram,
ChartType::BoxWhisker => ChartKind::BoxWhisker,
ChartType::Waterfall => ChartKind::Waterfall,
ChartType::Funnel => ChartKind::Funnel,
ChartType::Treemap => ChartKind::Treemap,
ChartType::Sunburst => ChartKind::Sunburst,
_ => return None,
};
let default_quartiles = if dc.inclusive_quartiles { QuartileMethod::Inclusive } else { QuartileMethod::Exclusive };
let data: Vec<(String, Option<String>, Option<String>)> = root
.child("chartData")
.and_then(|r| r.child("chartData"))
.map(|cd| {
cd.kids("data")
.map(|d| {
let id = d.attr("id").unwrap_or("").to_string();
let cat = d.kids("strDim").chain(d.kids("numDim")).find(|x| matches!(x.attr("type"), Some("cat" | "x"))).and_then(formula);
let val = d.kids("numDim").find(|x| matches!(x.attr("type"), Some("val" | "size" | "y"))).and_then(formula);
let cat =
d.kids("strDim").chain(d.kids("numDim")).find(|x| matches!(x.attr("type"), Some("cat" | "x"))).and_then(chartex_formula);
let val = d.kids("numDim").find(|x| matches!(x.attr("type"), Some("val" | "size" | "y"))).and_then(chartex_formula);
(id, cat, val)
})
.collect()
})
.unwrap_or_default();
let mut kind = None;
let mut series = vec![];
let mut data_labels = false;
for s in region.kids("series") {
let layout = s.attr("layoutId").unwrap_or("");
// A Pareto line belongs to its histogram.
if layout == "paretoLine" {
continue;
}
let k = kind_of(layout)?;
kind.get_or_insert(k);
let id = s.child_val("dataId").unwrap_or("");
let (cat, val) = data.iter().find(|(i, _, _)| i == id).map(|(_, c, v)| (c.clone(), v.clone())).unwrap_or_default();
data_labels |= s.path(&["dataLabels", "visibility"]).is_some_and(|v| v.flag("value", false));
series.push(Series {
quartiles: match s.path(&["layoutPr", "statistics"]).and_then(|el| el.attr("quartileMethod")) {
Some("inclusive") => QuartileMethod::Inclusive,
_ => QuartileMethod::Exclusive,
},
name: s.child("tx").and_then(text),
categories: cat,
values: val.unwrap_or_default(),
// The default colour (the series' theme accent, which the writer spells out) isn't kept.
color: s
.path(&["spPr", "solidFill"])
.and_then(dml_color)
.filter(|c| *c != gridcraft_model::Color::Theme(4 + (series.len() % 6) as u8, 0)),
..Default::default()
});
}
let legend = match chart.child("legend") {
let series_els: Vec<&El> = root
.and_then(|r| r.path(&["chart", "plotArea", "plotAreaRegion"]))
.map(|region| region.kids("series").filter(|s| s.attr("layoutId") != Some("paretoLine")).collect())
.unwrap_or_default();
let series = dc
.series
.into_iter()
.enumerate()
.map(|(idx, s)| {
let sel = series_els.get(idx).copied();
let (cat, val) = sel
.and_then(|el| el.child_val("dataId"))
.and_then(|id| data.iter().find(|(i, _, _)| i == id))
.map(|(_, c, v)| (c.clone(), v.clone()))
.unwrap_or_default();
let color = s
.fill
.as_ref()
.and_then(|f| match f {
craft_drawingml::style::Fill::Solid { color } => crate::chart::map_dml_color(color),
_ => None,
})
.or_else(|| sel.and_then(|el| el.path(&["spPr", "solidFill"])).and_then(crate::drawing::dml_color))
.filter(|c| *c != gridcraft_model::Color::Theme(4 + (idx % 6) as u8, 0));
let quartiles = sel
.and_then(|el| el.path(&["layoutPr", "statistics"]))
.and_then(|st| st.attr("quartileMethod"))
.map(|m| if m == "inclusive" { QuartileMethod::Inclusive } else { QuartileMethod::Exclusive })
.unwrap_or(default_quartiles);
let name = sel
.and_then(|el| el.child("tx"))
.and_then(chartex_text)
.or_else(|| s.refs.name.as_deref().map(crate::chart::chart_ref_from_file))
.or_else(|| (!s.name.is_empty()).then_some(s.name));
let categories = cat.or_else(|| s.refs.categories.as_deref().map(|f| crate::fmla::from_file(&crate::chart::chart_ref_from_file(f))));
let values =
val.or_else(|| s.refs.values.as_deref().map(|f| crate::fmla::from_file(&crate::chart::chart_ref_from_file(f)))).unwrap_or_default();
Series { quartiles, name, categories, values, color, ..Default::default() }
})
.collect();
let legend = match dc.legend.as_deref() {
None => LegendPos::None,
Some(l) => match l.attr("pos").unwrap_or("r") {
"b" => LegendPos::Bottom,
"t" => LegendPos::Top,
"l" => LegendPos::Left,
_ => LegendPos::Right,
},
Some("b") => LegendPos::Bottom,
Some("t") => LegendPos::Top,
Some("l") => LegendPos::Left,
Some(_) => LegendPos::Right,
};
let axis_title = |is_val: bool| -> Option<String> {
let pa = root?.path(&["chart", "plotArea"])?;
let ax = pa.kids("axis").find(|a| if is_val { a.child("valScaling").is_some() } else { a.child("catScaling").is_some() })?;
let title = ax.child("title")?;
if let Some(v) = title.path(&["tx", "txData", "v"]).map(|v| v.text.trim()).filter(|t| !t.is_empty()) {
return Some(v.to_string());
}
let rich = title.path(&["tx", "rich"])?;
let text: String = rich
.kids("p")
.map(|p| p.kids("r").filter_map(|r| r.child("t")).map(|t| t.text.as_str()).collect::<String>())
.collect::<Vec<_>>()
.join("\n");
(!text.trim().is_empty()).then_some(text)
};
let axis_title = |id: &str| plot.kids("axis").find(|a| a.attr("id") == Some(id)).and_then(|a| a.path(&["title", "tx"])).and_then(text);
Some(Chart {
id: 0,
kind: kind?,
kind,
anchor: Default::default(),
title: chart.path(&["title", "tx"]).and_then(text),
title: dc.title,
series,
legend,
data_labels,
data_labels: dc.data_labels,
data_table: None,
gridlines: plot.kids("axis").any(|a| a.child("majorGridlines").is_some()),
gridlines: dc.gridlines,
style: 2,
hole_size: 75,
first_slice_angle: 0,
x_title: axis_title("0"),
y_title: axis_title("1"),
x_title: dc.axis_titles.0.or_else(|| axis_title(false)),
y_title: dc.axis_titles.1.or_else(|| axis_title(true)),
source: None,
by_rows: false,
pivot: None,
})
}
pub fn read_chartex(root: &El) -> Option<Chart> {
let mut craft = crate::chart::to_craft_el(root);
if craft.child(craft_xml::Local("chartData")).is_none() {
craft.push(craft_xml::El::new("chartData").with_child(craft_xml::El::new("data").with_attr("id", "0")));
}
let dc = craft_drawingml::chart::chartex::chartex_from(&craft)?;
from_dml_chartex(dc, Some(root))
}
// ---------------------------------------------------------------- writing
/// Prefix of the hidden defined names chartex formulas go through: a chartex part refers to
+225 -194
View File
@@ -8,6 +8,7 @@
use std::fmt::Write as _;
use craft_xlsx::{Anchor as CraftAnchor, Drawing as CraftDrawing, Item as CraftItem, Marker as CraftMarker, Placement as CraftPlacement};
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS};
use gridcraft_model::{Anchor, AnchorMode, Color, Image, Shape, ShapeFormat, ShapeKind, ShapeTextAlign, ShapeTextAnchor, Sheet, Theme};
@@ -24,6 +25,10 @@ fn emu_px(v: Option<i64>) -> f32 {
v.map(|e| (e as f64 / EMU_PER_PX).clamp(-1e7, 1e7) as f32).unwrap_or(0.0)
}
fn emu_to_px(v: i64) -> f32 {
(v as f64 / EMU_PER_PX).clamp(-1e7, 1e7) as f32
}
pub(crate) fn marker(e: &El) -> (CellRef, f32, f32) {
let num = |n: &str| e.child(n).and_then(|c| c.text.trim().parse::<i64>().ok());
let col = num("col").unwrap_or(0).clamp(0, MAX_COLS as i64 - 1) as u32;
@@ -31,56 +36,64 @@ pub(crate) fn marker(e: &El) -> (CellRef, f32, f32) {
(CellRef::new(row, col), emu_px(num("colOff")).max(0.0), emu_px(num("rowOff")).max(0.0))
}
fn ext_px(e: Option<&El>) -> (f32, f32) {
match e {
Some(x) => (emu_px(x.attr_i64("cx")).max(0.0), emu_px(x.attr_i64("cy")).max(0.0)),
None => (0.0, 0.0),
}
fn craft_marker(m: CraftMarker) -> (CellRef, f32, f32) {
let col = m.col.min(MAX_COLS - 1);
let row = m.row.min(MAX_ROWS - 1);
(CellRef::new(row, col), emu_to_px(m.col_off).max(0.0), emu_to_px(m.row_off).max(0.0))
}
fn read_anchor(a: &El, sheet: &Sheet) -> Option<Anchor> {
match a.name.as_str() {
"twoCellAnchor" => {
let (cell, dx, dy) = marker(a.child("from")?);
let (to, tdx, tdy) = a.child("to").map(marker).unwrap_or((cell, dx, dy));
fn placement_to_anchor(p: &CraftPlacement, sheet: &Sheet) -> Anchor {
match p {
CraftPlacement::TwoCell { from, to, edit_as } => {
let (cell, dx, dy) = craft_marker(*from);
let (to, tdx, tdy) = craft_marker(*to);
let x1 = sheet.col_left(cell.col) + dx as f64;
let y1 = sheet.row_top(cell.row) + dy as f64;
let x2 = sheet.col_left(to.col) + tdx as f64;
let y2 = sheet.row_top(to.row) + tdy as f64;
// Excel stores "Move and size with cells" as a plain twoCellAnchor, "Move but don't
// size" as editAs="oneCell", and "Don't move or size" as editAs="absolute".
let mode = match a.attr("editAs") {
let mode = match edit_as.as_deref() {
Some("absolute") => AnchorMode::Absolute,
Some("oneCell") => AnchorMode::MoveOnly,
_ => AnchorMode::MoveAndSize,
};
Some(Anchor { cell, dx, dy, width: (x2 - x1).max(0.0) as f32, height: (y2 - y1).max(0.0) as f32, mode })
Anchor { cell, dx, dy, width: (x2 - x1).max(0.0) as f32, height: (y2 - y1).max(0.0) as f32, mode }
}
"oneCellAnchor" => {
let (cell, dx, dy) = marker(a.child("from")?);
let (width, height) = ext_px(a.child("ext"));
Some(Anchor { cell, dx, dy, width, height, mode: AnchorMode::MoveOnly })
CraftPlacement::OneCell { from, cx, cy } => {
let (cell, dx, dy) = craft_marker(*from);
Anchor { cell, dx, dy, width: emu_to_px(*cx).max(0.0), height: emu_to_px(*cy).max(0.0), mode: AnchorMode::MoveOnly }
}
"absoluteAnchor" => {
let pos = a.child("pos");
let x = emu_px(pos.and_then(|p| p.attr_i64("x"))).max(0.0) as f64;
let y = emu_px(pos.and_then(|p| p.attr_i64("y"))).max(0.0) as f64;
CraftPlacement::Absolute { x, y, cx, cy } => {
let x = emu_to_px(*x).max(0.0) as f64;
let y = emu_to_px(*y).max(0.0) as f64;
let col = sheet.col_at(x);
let row = sheet.row_at(y);
let (width, height) = ext_px(a.child("ext"));
Some(Anchor {
Anchor {
cell: CellRef::new(row, col),
dx: (x - sheet.col_left(col)).max(0.0) as f32,
dy: (y - sheet.row_top(row)).max(0.0) as f32,
width,
height,
width: emu_to_px(*cx).max(0.0),
height: emu_to_px(*cy).max(0.0),
mode: AnchorMode::Absolute,
})
}
}
_ => None,
}
}
fn from_craft_el(e: &craft_xml::El) -> El {
let name = e.name.split_once(':').map_or(e.name.as_str(), |(_, local)| local).to_string();
let attrs = e.attrs.iter().map(|(k, v)| (k.split_once(':').map_or(k.as_str(), |(_, local)| local).to_string(), v.clone())).collect();
let mut children = Vec::new();
let mut text = String::new();
for node in &e.children {
match node {
craft_xml::Node::El(c) => children.push(from_craft_el(c)),
craft_xml::Node::Text(t) | craft_xml::Node::CData(t) => text.push_str(t),
craft_xml::Node::Pi { .. } | craft_xml::Node::Comment(_) => {}
}
}
El { name, attrs, children, text }
}
/// Colour of a DrawingML colour choice inside `e` (e.g. a `solidFill`).
pub fn dml_color(e: &El) -> Option<Color> {
if let Some(c) = e.child("srgbClr").and_then(|c| c.attr("val")) {
@@ -127,32 +140,53 @@ fn mime_for(name: &str) -> &'static str {
}
pub fn read_drawing(cx: &mut Ctx<'_>, part: &str, sheet: &mut Sheet) -> Result<(), IoError> {
let Some(x) = cx.optional_xml(part)? else { return Ok(()) };
let Some(bytes) = cx.pkg.read(part)? else {
cx.warn(format!("missing part {part}"));
return Ok(());
};
let opts = craft_xml::Options::canonical(&craft_xlsx::ns::CANONICAL).with_limits(craft_xml::Limits {
max_input: crate::package::MAX_PART as usize,
max_depth: crate::xml::MAX_DEPTH,
max_nodes: crate::xml::MAX_XML_NODES,
..craft_xml::Limits::DEFAULT
});
let root = match opts.parse(&bytes) {
Ok(r) => r,
Err(e) if e.is_limit() => return Err(IoError::TooLarge(format!("{part}: {e}"))),
Err(e) => {
cx.warn(format!("skipped {part}: {e}"));
return Ok(());
}
};
let dr = CraftDrawing::read(&root);
let rels = cx.pkg.rels(part)?;
for (n, a) in x.children.iter().enumerate() {
let Some(anchor) = read_anchor(a, sheet) else { continue };
let mut anchors: Vec<&CraftAnchor> = Vec::new();
let mut alt_anchors: Vec<CraftAnchor> = Vec::new();
for item in &dr.items {
match item {
CraftItem::Anchor(a) => anchors.push(a),
CraftItem::Other(e) if e.name == "mc:AlternateContent" => {
alt_anchors.extend(CraftDrawing::alternate_anchors(e));
}
CraftItem::Other(_) => {}
}
}
for (n, craft_a) in anchors.into_iter().chain(alt_anchors.iter()).enumerate() {
let anchor = placement_to_anchor(&craft_a.placement, sheet);
let n = n + 1;
// Objects in markup-compatibility blocks: the first choice (chartex frames, or Office Math
// that converts to LaTeX), else the fallback.
let objs: Vec<&El> = a
.children
.iter()
.flat_map(|o| match o.name.as_str() {
"AlternateContent" => o
.child("Choice")
.filter(|c| {
// Office Math is taken only when the box holds one equation that
// converts: otherwise the fallback (a picture or text from the writer)
// keeps everything visible.
c.child("graphicFrame").is_some()
|| c.child("sp").and_then(|sp| sp.child("txBody")).and_then(crate::omml::equation_source).is_some()
})
.or_else(|| o.child("Fallback"))
.map(|c| c.children.iter().collect())
.unwrap_or_default(),
_ => vec![o],
})
.collect();
let obj_el = from_craft_el(&craft_a.object);
let objs: Vec<&El> = match obj_el.name.as_str() {
"AlternateContent" => obj_el
.child("Choice")
.filter(|c| {
c.child("graphicFrame").is_some()
|| c.child("sp").and_then(|sp| sp.child("txBody")).and_then(crate::omml::equation_source).is_some()
})
.or_else(|| obj_el.child("Fallback"))
.map(|c| c.children.iter().collect())
.unwrap_or_default(),
_ => vec![&obj_el],
};
for obj in objs {
match obj.name.as_str() {
"pic" => {
@@ -475,12 +509,7 @@ fn holds_written_text(tb: &El, src: &str) -> bool {
crate::xml::parse(written.as_bytes()).is_ok_and(|w| body_text(&w) == body_text(tb))
}
/// The opening `<xdr:twoCellAnchor>` for a model anchor, carrying Excel's `editAs` when the mode
/// is not the default: omitted for "Move and size with cells", `editAs="oneCell"` for "Move but
/// don't size", `editAs="absolute"` for "Don't move or size". (Excel writes pictures this way;
/// the standalone `oneCellAnchor`/`absoluteAnchor` elements are read on import but not written.)
/// Returns the opening tag and the matching closing tag.
fn anchor_open(sheet: &Sheet, a: &Anchor) -> (String, &'static str) {
fn to_placement(sheet: &Sheet, a: &Anchor) -> CraftPlacement {
let px = |v: f64| ((v.max(0.0)) * EMU_PER_PX).round() as i64;
let x1 = sheet.col_left(a.cell.col) + a.dx as f64;
let y1 = sheet.row_top(a.cell.row) + a.dy as f64;
@@ -490,21 +519,26 @@ fn anchor_open(sheet: &Sheet, a: &Anchor) -> (String, &'static str) {
let tr = sheet.row_at(y2);
let tdx = x2 - sheet.col_left(tc);
let tdy = y2 - sheet.row_top(tr);
let edit = match a.mode {
AnchorMode::MoveAndSize => "",
AnchorMode::MoveOnly => " editAs=\"oneCell\"",
AnchorMode::Absolute => " editAs=\"absolute\"",
let edit_as = match a.mode {
AnchorMode::MoveAndSize => None,
AnchorMode::MoveOnly => Some("oneCell".to_string()),
AnchorMode::Absolute => Some("absolute".to_string()),
};
let open = format!(
"<xdr:twoCellAnchor{edit}><xdr:from><xdr:col>{}</xdr:col><xdr:colOff>{}</xdr:colOff><xdr:row>{}</xdr:row><xdr:rowOff>{}</xdr:rowOff></xdr:from><xdr:to><xdr:col>{tc}</xdr:col><xdr:colOff>{}</xdr:colOff><xdr:row>{tr}</xdr:row><xdr:rowOff>{}</xdr:rowOff></xdr:to>",
a.cell.col,
px(a.dx as f64),
a.cell.row,
px(a.dy as f64),
px(tdx),
px(tdy)
);
(open, "</xdr:twoCellAnchor>")
CraftPlacement::TwoCell {
from: CraftMarker { col: a.cell.col, col_off: px(a.dx as f64), row: a.cell.row, row_off: px(a.dy as f64) },
to: CraftMarker { col: tc, col_off: px(tdx), row: tr, row_off: px(tdy) },
edit_as,
}
}
fn parse_craft_fragment(xml: &str) -> Option<craft_xml::El> {
let opts = craft_xml::Options::default().with_limits(craft_xml::Limits {
max_input: crate::package::MAX_PART as usize,
max_depth: crate::xml::MAX_DEPTH,
max_nodes: crate::xml::MAX_XML_NODES,
..craft_xml::Limits::DEFAULT
});
opts.parse(xml.as_bytes()).ok()
}
fn xfrm(a: &Anchor, tag: &str) -> String {
@@ -533,151 +567,148 @@ pub enum Obj<'a> {
/// The drawing part for a sheet's objects (relationship ids already assigned).
pub fn write_drawing(sheet: &Sheet, theme: &Theme, objs: &[Obj<'_>]) -> String {
let mut s = String::from(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<xdr:wsDr xmlns:xdr=\"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\">",
);
let mut items = Vec::with_capacity(objs.len());
for (i, o) in objs.iter().enumerate() {
let id = i + 2;
let close_tag;
match o {
Obj::Image(img, rid) => {
let (open, close) = anchor_open(sheet, &img.anchor);
close_tag = close;
s.push_str(&open);
let _ = write!(
s,
"<xdr:pic><xdr:nvPicPr><xdr:cNvPr id=\"{id}\" name=\"Picture {}\" descr=\"{}\"/><xdr:cNvPicPr><a:picLocks noChangeAspect=\"1\"/></xdr:cNvPicPr></xdr:nvPicPr><xdr:blipFill><a:blip r:embed=\"{rid}\"/><a:stretch><a:fillRect/></a:stretch></xdr:blipFill><xdr:spPr>{}<a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic>",
id - 1,
esc_attr(&img.alt),
xfrm(&img.anchor, "a:xfrm")
);
let placement = to_placement(sheet, &img.anchor);
let mut anchor = CraftAnchor::picture(placement, id as u32, &format!("Picture {}", id - 1), &img.alt, rid);
if let Some(ext) = anchor.object.child_mut("xdr:spPr").and_then(|sp| sp.child_mut("a:xfrm")).and_then(|x| x.child_mut("a:ext")) {
let e = |v: f32| ((v.max(0.0) as f64) * EMU_PER_PX).round() as i64;
ext.set_attr("cx", e(img.anchor.width));
ext.set_attr("cy", e(img.anchor.height));
}
items.push(CraftItem::Anchor(anchor));
}
Obj::Chart(ch, rid) if crate::chartex::is_chartex(ch.kind) => {
// Chartex frames come with a fallback for readers that don't know them.
let (open, close) = anchor_open(sheet, &ch.anchor);
close_tag = close;
s.push_str(&open);
let placement = to_placement(sheet, &ch.anchor);
let (prefix, ns) = crate::chartex::requires(ch.kind);
let _ = write!(
s,
let xml = format!(
"<mc:AlternateContent xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"><mc:Choice xmlns:{prefix}=\"{ns}\" Requires=\"{prefix}\"><xdr:graphicFrame macro=\"\"><xdr:nvGraphicFramePr><xdr:cNvPr id=\"{id}\" name=\"Chart {}\"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr>{}<a:graphic><a:graphicData uri=\"http://schemas.microsoft.com/office/drawing/2014/chartex\"><cx:chart xmlns:cx=\"http://schemas.microsoft.com/office/drawing/2014/chartex\" r:id=\"{rid}\"/></a:graphicData></a:graphic></xdr:graphicFrame></mc:Choice><mc:Fallback><xdr:sp macro=\"\" textlink=\"\"><xdr:nvSpPr><xdr:cNvPr id=\"0\" name=\"\"/><xdr:cNvSpPr><a:spLocks noTextEdit=\"1\"/></xdr:cNvSpPr></xdr:nvSpPr><xdr:spPr>{}<a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></xdr:spPr><xdr:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr lang=\"en-US\"/><a:t>This chart type can't be shown by this application.</a:t></a:r></a:p></xdr:txBody></xdr:sp></mc:Fallback></mc:AlternateContent>",
id - 1,
xfrm(&ch.anchor, "xdr:xfrm"),
xfrm(&ch.anchor, "a:xfrm")
);
if let Some(object) = parse_craft_fragment(&xml) {
items.push(CraftItem::Anchor(CraftAnchor { placement, object, client_data: None }));
}
}
Obj::Chart(ch, rid) => {
let (open, close) = anchor_open(sheet, &ch.anchor);
close_tag = close;
s.push_str(&open);
let _ = write!(
s,
"<xdr:graphicFrame macro=\"\"><xdr:nvGraphicFramePr><xdr:cNvPr id=\"{id}\" name=\"Chart {}\"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr>{}<a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"><c:chart r:id=\"{rid}\"/></a:graphicData></a:graphic></xdr:graphicFrame>",
id - 1,
xfrm(&ch.anchor, "xdr:xfrm")
);
let placement = to_placement(sheet, &ch.anchor);
let mut anchor = CraftAnchor::chart(placement, id as u32, &format!("Chart {}", id - 1), rid);
if let Some(ext) = anchor.object.child_mut("xdr:xfrm").and_then(|x| x.child_mut("a:ext")) {
let e = |v: f32| ((v.max(0.0) as f64) * EMU_PER_PX).round() as i64;
ext.set_attr("cx", e(ch.anchor.width));
ext.set_attr("cy", e(ch.anchor.height));
}
items.push(CraftItem::Anchor(anchor));
}
Obj::Shape(sh) if sh.kind == ShapeKind::Equation => {
let (open, close) = anchor_open(sheet, &sh.anchor);
close_tag = close;
s.push_str(&open);
write_equation(&mut s, sh, id, theme);
let placement = to_placement(sheet, &sh.anchor);
let mut xml = String::new();
write_equation(&mut xml, sh, id, theme);
if let Some(object) = parse_craft_fragment(&xml) {
items.push(CraftItem::Anchor(CraftAnchor { placement, object, client_data: None }));
}
}
Obj::Shape(sh) => {
let (open, close) = anchor_open(sheet, &sh.anchor);
close_tag = close;
s.push_str(&open);
if let Some(xml) = ink::write(sh, theme, id) {
s.push_str(&xml);
s.push_str("<xdr:clientData/>");
s.push_str(close_tag);
continue;
}
let (prst, tx) = match sh.kind {
ShapeKind::Rectangle => ("rect", false),
ShapeKind::RoundedRectangle => ("roundRect", false),
ShapeKind::Ellipse => ("ellipse", false),
ShapeKind::Triangle => ("triangle", false),
ShapeKind::Line | ShapeKind::Arrow => ("line", false),
// Equations are written by `write_equation`; this arm keeps the match whole.
ShapeKind::TextBox | ShapeKind::WordArt | ShapeKind::Equation => ("rect", true),
ShapeKind::Icon | ShapeKind::Ink => ("rect", false),
let placement = to_placement(sheet, &sh.anchor);
let xml = if let Some(xml) = ink::write(sh, theme, id) {
xml
} else {
let mut s = String::new();
write_plain_shape(&mut s, sh, id, theme);
s
};
let _ = write!(
s,
"<xdr:sp macro=\"\" textlink=\"\"><xdr:nvSpPr><xdr:cNvPr id=\"{id}\" name=\"Shape {}\"/><xdr:cNvSpPr{}/></xdr:nvSpPr><xdr:spPr>{}<a:prstGeom prst=\"{prst}\"><a:avLst/></a:prstGeom>",
id - 1,
if tx { " txBox=\"1\"" } else { "" },
xfrm_rot(&sh.anchor, "a:xfrm", sh.rotation)
);
if let Some(c) = srgb(&sh.fill, theme) {
let _ = write!(s, "<a:solidFill>{c}</a:solidFill>");
if let Some(object) = parse_craft_fragment(&xml) {
items.push(CraftItem::Anchor(CraftAnchor { placement, object, client_data: None }));
}
let line_c = srgb(&sh.line, theme);
if sh.format.no_line {
s.push_str("<a:ln><a:noFill/></a:ln>");
} else if line_c.is_some() || sh.kind == ShapeKind::Arrow {
s.push_str("<a:ln w=\"9525\">");
match line_c {
Some(c) => {
let _ = write!(s, "<a:solidFill>{c}</a:solidFill>");
}
None => s.push_str("<a:solidFill><a:srgbClr val=\"000000\"/></a:solidFill>"),
}
if sh.kind == ShapeKind::Arrow {
s.push_str("<a:tailEnd type=\"triangle\"/>");
}
s.push_str("</a:ln>");
}
s.push_str("</xdr:spPr>");
// A WordArt with no text still writes its body, which carries the WordArt marker.
if !sh.text.is_empty() || sh.kind == ShapeKind::WordArt {
let f = &sh.format;
let anchor = match f.anchor {
Some(ShapeTextAnchor::Top) => " anchor=\"t\"",
Some(ShapeTextAnchor::Middle) => " anchor=\"ctr\"",
Some(ShapeTextAnchor::Bottom) => " anchor=\"b\"",
None if sh.kind == ShapeKind::TextBox => " anchor=\"t\"",
None => "",
};
if sh.kind == ShapeKind::WordArt {
// Our WordArt marker: a (non-warping) text warp, which the reader maps back to WordArt.
let _ = write!(
s,
"<xdr:txBody><a:bodyPr wrap=\"square\" rtlCol=\"0\"{anchor}><a:prstTxWarp prst=\"textNoShape\"><a:avLst/></a:prstTxWarp></a:bodyPr><a:lstStyle/>"
);
} else {
let _ = write!(s, "<xdr:txBody><a:bodyPr wrap=\"square\" rtlCol=\"0\"{anchor}/><a:lstStyle/>");
}
let algn = match f.align {
None => "",
Some(ShapeTextAlign::Left) => " algn=\"l\"",
Some(ShapeTextAlign::Center) => " algn=\"ctr\"",
Some(ShapeTextAlign::Right) => " algn=\"r\"",
};
let rtl = if f.rtl { " rtl=\"1\"" } else { "" };
let ppr = if algn.is_empty() && rtl.is_empty() { String::new() } else { format!("<a:pPr{algn}{rtl}/>") };
let (rpr_attrs, rpr_body) = run_props(f, theme);
for line in sh.text.split('\n') {
if line.is_empty() {
let _ = write!(s, "<a:p>{ppr}<a:endParaRPr lang=\"en-US\"{rpr_attrs}/></a:p>");
} else if rpr_body.is_empty() {
let _ = write!(s, "<a:p>{ppr}<a:r><a:rPr lang=\"en-US\"{rpr_attrs}/><a:t>{}</a:t></a:r></a:p>", esc(line));
} else {
let _ =
write!(s, "<a:p>{ppr}<a:r><a:rPr lang=\"en-US\"{rpr_attrs}>{rpr_body}</a:rPr><a:t>{}</a:t></a:r></a:p>", esc(line));
}
}
s.push_str("</xdr:txBody>");
}
s.push_str("</xdr:sp>");
}
}
s.push_str("<xdr:clientData/>");
s.push_str(close_tag);
}
s.push_str("</xdr:wsDr>");
s
let dr = CraftDrawing { items, attrs: Vec::new() };
String::from_utf8_lossy(&dr.to_xml()).into_owned()
}
fn write_plain_shape(s: &mut String, sh: &Shape, id: usize, theme: &Theme) {
let (prst, tx) = match sh.kind {
ShapeKind::Rectangle => ("rect", false),
ShapeKind::RoundedRectangle => ("roundRect", false),
ShapeKind::Ellipse => ("ellipse", false),
ShapeKind::Triangle => ("triangle", false),
ShapeKind::Line | ShapeKind::Arrow => ("line", false),
// Equations are written by `write_equation`; this arm keeps the match whole.
ShapeKind::TextBox | ShapeKind::WordArt | ShapeKind::Equation => ("rect", true),
ShapeKind::Icon | ShapeKind::Ink => ("rect", false),
};
let _ = write!(
s,
"<xdr:sp macro=\"\" textlink=\"\"><xdr:nvSpPr><xdr:cNvPr id=\"{id}\" name=\"Shape {}\"/><xdr:cNvSpPr{}/></xdr:nvSpPr><xdr:spPr>{}<a:prstGeom prst=\"{prst}\"><a:avLst/></a:prstGeom>",
id - 1,
if tx { " txBox=\"1\"" } else { "" },
xfrm_rot(&sh.anchor, "a:xfrm", sh.rotation)
);
if let Some(c) = srgb(&sh.fill, theme) {
let _ = write!(s, "<a:solidFill>{c}</a:solidFill>");
}
let line_c = srgb(&sh.line, theme);
if sh.format.no_line {
s.push_str("<a:ln><a:noFill/></a:ln>");
} else if line_c.is_some() || sh.kind == ShapeKind::Arrow {
s.push_str("<a:ln w=\"9525\">");
match line_c {
Some(c) => {
let _ = write!(s, "<a:solidFill>{c}</a:solidFill>");
}
None => s.push_str("<a:solidFill><a:srgbClr val=\"000000\"/></a:solidFill>"),
}
if sh.kind == ShapeKind::Arrow {
s.push_str("<a:tailEnd type=\"triangle\"/>");
}
s.push_str("</a:ln>");
}
s.push_str("</xdr:spPr>");
// A WordArt with no text still writes its body, which carries the WordArt marker.
if !sh.text.is_empty() || sh.kind == ShapeKind::WordArt {
let f = &sh.format;
let anchor = match f.anchor {
Some(ShapeTextAnchor::Top) => " anchor=\"t\"",
Some(ShapeTextAnchor::Middle) => " anchor=\"ctr\"",
Some(ShapeTextAnchor::Bottom) => " anchor=\"b\"",
None if sh.kind == ShapeKind::TextBox => " anchor=\"t\"",
None => "",
};
if sh.kind == ShapeKind::WordArt {
// Our WordArt marker: a (non-warping) text warp, which the reader maps back to WordArt.
let _ = write!(
s,
"<xdr:txBody><a:bodyPr wrap=\"square\" rtlCol=\"0\"{anchor}><a:prstTxWarp prst=\"textNoShape\"><a:avLst/></a:prstTxWarp></a:bodyPr><a:lstStyle/>"
);
} else {
let _ = write!(s, "<xdr:txBody><a:bodyPr wrap=\"square\" rtlCol=\"0\"{anchor}/><a:lstStyle/>");
}
let algn = match f.align {
None => "",
Some(ShapeTextAlign::Left) => " algn=\"l\"",
Some(ShapeTextAlign::Center) => " algn=\"ctr\"",
Some(ShapeTextAlign::Right) => " algn=\"r\"",
};
let rtl = if f.rtl { " rtl=\"1\"" } else { "" };
let ppr = if algn.is_empty() && rtl.is_empty() { String::new() } else { format!("<a:pPr{algn}{rtl}/>") };
let (rpr_attrs, rpr_body) = run_props(f, theme);
for line in sh.text.split('\n') {
if line.is_empty() {
let _ = write!(s, "<a:p>{ppr}<a:endParaRPr lang=\"en-US\"{rpr_attrs}/></a:p>");
} else if rpr_body.is_empty() {
let _ = write!(s, "<a:p>{ppr}<a:r><a:rPr lang=\"en-US\"{rpr_attrs}/><a:t>{}</a:t></a:r></a:p>", esc(line));
} else {
let _ = write!(s, "<a:p>{ppr}<a:r><a:rPr lang=\"en-US\"{rpr_attrs}>{rpr_body}</a:rPr><a:t>{}</a:t></a:r></a:p>", esc(line));
}
}
s.push_str("</xdr:txBody>");
}
s.push_str("</xdr:sp>");
}
/// A text run's `a:rPr` attributes (size, bold, italic) and children in schema order (outline,
+18 -1
View File
@@ -18,6 +18,7 @@ const LIMITS: craft_opc::Limits = craft_opc::Limits::new(MAX_ENTRIES, MAX_PART,
pub struct Package<'a> {
opc: craft_opc::LazyPackage<'a>,
craft: craft_xlsx::Package<'a>,
}
/// A relationship.
@@ -46,9 +47,25 @@ fn error(e: craft_opc::Error) -> IoError {
}
}
/// GridCraft's wording of a `craft-xlsx` error.
pub(crate) fn craft_error(e: craft_xlsx::Error) -> IoError {
match e {
craft_xlsx::Error::Zip(m) => IoError::Zip(m),
craft_xlsx::Error::Xml(m) => IoError::Xml(m),
craft_xlsx::Error::Invalid(m) => IoError::Format(m),
craft_xlsx::Error::TooLarge(m) => IoError::TooLarge(m),
}
}
impl<'a> Package<'a> {
pub fn open(bytes: &'a [u8]) -> Result<Package<'a>, IoError> {
Ok(Package { opc: craft_opc::LazyPackage::open(bytes, &LIMITS).map_err(error)? })
let opc = craft_opc::LazyPackage::open(bytes, &LIMITS).map_err(error)?;
let craft = craft_xlsx::Package::open(bytes, &craft_xlsx::Limits::default()).map_err(craft_error)?;
Ok(Package { opc, craft })
}
pub(crate) fn craft_mut(&mut self) -> &mut craft_xlsx::Package<'a> {
&mut self.craft
}
/// Every part's (normalized) name, sorted.
File diff suppressed because it is too large Load Diff
+93 -177
View File
@@ -1,49 +1,104 @@
use super::{
AutoFilter, CellRef, Comment, Ctx, El, FilterCriterion, HashMap, Hyperlink, LinkBudget, MAX_COLS, MAX_HYPERLINK_BYTES, MAX_HYPERLINK_CELLS,
MAX_HYPERLINK_TARGET, MAX_ROWS, MAX_TOOLTIP_CHARS, NoteBox, NoteCorner, RangeRef, Rel, Sheet, Table, TableColumn, TotalsFn, XmlColumnPr,
from_file, truncate_chars, xml,
AutoFilter, CellRef, Comment, Ctx, El, FilterCriterion, HashMap, MAX_COLS, MAX_ROWS, NoteBox, NoteCorner, RangeRef, Sheet, Table, TableColumn,
TotalsFn, XmlColumnPr, from_file, xml,
};
/// `rels` maps relationship ids to relationships (the first of duplicate ids). `budget` counts the
/// cells and bytes this sheet's hyperlinks have copied so far, across `<hyperlinks>` blocks.
pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &HashMap<&str, &Rel>, sheet: &mut Sheet, budget: &mut LinkBudget) {
for h in e.kids("hyperlink") {
let Some(range) = h.attr("ref").and_then(RangeRef::parse) else { continue };
let rel_target = h.attr("id").and_then(|id| rels.get(id)).map(|r| r.target.as_str()).unwrap_or("");
let location = h.attr("location").filter(|l| !l.is_empty());
// Each covered cell gets its own copy of the link: refuse oversized targets before copying.
if rel_target.len().saturating_add(location.map_or(0, str::len)) > MAX_HYPERLINK_TARGET {
cx.warn(format!("sheet \"{name}\": hyperlinks longer than {MAX_HYPERLINK_TARGET} characters were dropped"));
continue;
}
let mut target = rel_target.to_string();
// A relationship is a file or web page; a bare `location` is a place in this workbook.
let external = !target.is_empty();
if let Some(loc) = location {
if target.is_empty() {
target = loc.trim_start_matches('#').to_string();
} else {
target = format!("{target}#{loc}");
pub(super) fn from_craft_table(cx: &mut Ctx<'_>, t: &craft_xlsx::Table) -> Table {
let columns = t
.columns
.iter()
.map(|c| {
let totals = match c.totals_row_function.as_deref().unwrap_or("none") {
"average" => TotalsFn::Average,
"count" => TotalsFn::Count,
"countNums" => TotalsFn::CountNums,
"max" => TotalsFn::Max,
"min" => TotalsFn::Min,
"sum" => TotalsFn::Sum,
"stdDev" => TotalsFn::StdDev,
"var" => TotalsFn::Var,
"custom" => TotalsFn::Custom,
_ => TotalsFn::None,
};
let totals_label =
if totals == TotalsFn::Custom { c.totals_row_formula.as_ref().map(|(f, _)| from_file(f.trim())) } else { c.totals_row_label.clone() };
let xml = c.other.iter().find(|e| e.name == "xmlColumnPr").and_then(|x| {
Some(XmlColumnPr {
map_id: x.attr_u32("mapId")?,
xpath: x.attr("xpath")?.to_string(),
data_type: x.attr("xmlDataType").unwrap_or("string").to_string(),
denormalized: x.flag("denormalized", false),
})
});
TableColumn {
name: xml::decode_xstring(c.name.as_deref().unwrap_or("")),
totals,
totals_label,
formula: c.calculated_formula.as_ref().map(|(f, _)| from_file(f.trim())),
unique_name: c.unique_name.clone(),
xml,
}
})
.collect();
let xml_table = t.table_type.as_deref() == Some("xml");
let si = t.style.as_ref();
let filter = t.auto_filter.as_ref().and_then(|af| read_autofilter(cx, &super::from_craft_el(af))).map(|af| af.criteria).unwrap_or_default();
Table {
id: t.id.unwrap_or(0),
name: t.display_name.as_deref().or(t.name.as_deref()).unwrap_or("Table").to_string(),
range: super::to_range_ref(t.range),
header_row: t.header_row_count.unwrap_or(1) > 0,
totals_row: t.totals_row_count.unwrap_or(0) > 0,
columns,
style: si.and_then(|s| s.name.as_deref()).unwrap_or("").to_string(),
banded_rows: si.is_some_and(|s| s.show_row_stripes.unwrap_or(false)),
banded_cols: si.is_some_and(|s| s.show_column_stripes.unwrap_or(false)),
first_col: si.is_some_and(|s| s.show_first_column.unwrap_or(false)),
last_col: si.is_some_and(|s| s.show_last_column.unwrap_or(false)),
filter_button: t.auto_filter.is_some(),
filter,
table_type: xml_table.then(|| "xml".to_string()),
connection_id: t.connection_id.filter(|_| xml_table),
}
}
pub(super) fn apply_craft_comments(comments: &craft_xlsx::Comments, sheet: &mut Sheet) {
for c in &comments.comments {
let cell = CellRef::new(c.at.row, c.at.col);
let author = comments.author(c).unwrap_or("").to_string();
let mut text = c.text.text.to_string();
if !author.is_empty()
&& let Some(rest) = text.strip_prefix(&format!("{author}:"))
{
text = rest.strip_prefix('\n').unwrap_or(rest).to_string();
}
if target.is_empty() {
continue;
sheet
.comments
.insert(cell, Comment { author, text, replies: vec![], threaded: false, resolved: false, visible: false, dates: vec![], note_box: None });
}
}
pub(super) fn apply_craft_note_shapes(shapes: &[craft_xlsx::NoteShape], sheet: &mut Sheet) {
for s in shapes {
let cell = CellRef::new(s.at.row, s.at.col);
let Some(c) = sheet.comments.get_mut(&cell) else { continue };
if s.visible && !c.threaded {
c.visible = true;
}
let tooltip = h.attr("tooltip").map(|t| truncate_chars(t, MAX_TOOLTIP_CHARS));
let link_bytes = (target.len() + tooltip.as_ref().map_or(0, String::len)) as u64;
let link = Hyperlink { target, tooltip, external };
for c in range.iter() {
if budget.cells >= MAX_HYPERLINK_CELLS {
cx.warn(format!("sheet \"{name}\": hyperlinks past the first {MAX_HYPERLINK_CELLS} cells were dropped"));
return;
}
if budget.bytes.saturating_add(link_bytes) > MAX_HYPERLINK_BYTES {
cx.warn(format!("sheet \"{name}\": hyperlink targets past {MAX_HYPERLINK_BYTES} bytes were dropped"));
return;
}
budget.cells += 1;
budget.bytes += link_bytes;
sheet.hyperlinks.insert(c, link.clone());
if let Some([c1, dx1, r1, dy1, c2, dx2, r2, dy2]) = s.anchor
&& c1.max(c2) < MAX_COLS
&& r1.max(r2) < MAX_ROWS
{
let corner = |col: u32, col_px: u32, row: u32, row_px: u32| NoteCorner {
col: i64::from(col) - i64::from(cell.col),
col_px,
row: i64::from(row) - i64::from(cell.row),
row_px,
};
let nb = NoteBox { from: corner(c1, dx1, r1, dy1), to: corner(c2, dx2, r2, dy2), size_pt: s.size_pt };
c.note_box = (nb != crate::sheet_write::DEFAULT_NOTE_BOX).then_some(nb);
}
}
}
@@ -102,145 +157,6 @@ pub fn read_autofilter(cx: &mut Ctx<'_>, e: &El) -> Option<AutoFilter> {
Some(AutoFilter { range, criteria })
}
pub fn read_table(cx: &mut Ctx<'_>, x: &El) -> Option<Table> {
let range = x.attr("ref").and_then(RangeRef::parse)?;
let name = x.attr("displayName").or_else(|| x.attr("name")).unwrap_or("Table").to_string();
let header_row = x.attr_u32("headerRowCount").unwrap_or(1) > 0;
let totals_row = x.attr_u32("totalsRowCount").unwrap_or(0) > 0;
let columns = x
.child("tableColumns")
.map(|tc| {
tc.kids("tableColumn")
.map(|c| {
let totals = match c.attr("totalsRowFunction").unwrap_or("none") {
"average" => TotalsFn::Average,
"count" => TotalsFn::Count,
"countNums" => TotalsFn::CountNums,
"max" => TotalsFn::Max,
"min" => TotalsFn::Min,
"sum" => TotalsFn::Sum,
"stdDev" => TotalsFn::StdDev,
"var" => TotalsFn::Var,
"custom" => TotalsFn::Custom,
_ => TotalsFn::None,
};
let totals_label = if totals == TotalsFn::Custom {
c.child("totalsRowFormula").map(|f| from_file(f.text.trim()))
} else {
c.attr("totalsRowLabel").map(str::to_string)
};
TableColumn {
name: xml::decode_xstring(c.attr("name").unwrap_or("")),
totals,
totals_label,
formula: c.child("calculatedColumnFormula").map(|f| from_file(f.text.trim())),
unique_name: c.attr("uniqueName").map(str::to_string),
xml: c.child("xmlColumnPr").and_then(|x| {
Some(XmlColumnPr {
map_id: x.attr_u32("mapId")?,
xpath: x.attr("xpath")?.to_string(),
data_type: x.attr("xmlDataType").unwrap_or("string").to_string(),
denormalized: x.flag("denormalized", false),
})
}),
}
})
.collect()
})
.unwrap_or_default();
let si = x.child("tableStyleInfo");
// Only XML tables are kept as such: a query table's definition hangs off the table part, which
// is rewritten, so it would lose it.
let xml_table = x.attr("tableType") == Some("xml");
Some(Table {
id: x.attr_u32("id").unwrap_or(0),
name,
range,
header_row,
totals_row,
columns,
style: si.and_then(|s| s.attr("name")).unwrap_or("").to_string(),
banded_rows: si.is_some_and(|s| s.flag("showRowStripes", false)),
banded_cols: si.is_some_and(|s| s.flag("showColumnStripes", false)),
first_col: si.is_some_and(|s| s.flag("showFirstColumn", false)),
last_col: si.is_some_and(|s| s.flag("showLastColumn", false)),
filter_button: x.child("autoFilter").is_some(),
filter: x.child("autoFilter").and_then(|e| read_autofilter(cx, e)).map(|af| af.criteria).unwrap_or_default(),
table_type: xml_table.then(|| "xml".to_string()),
connection_id: x.attr_u32("connectionId").filter(|_| xml_table),
})
}
pub(super) fn read_comments(x: &El, sheet: &mut Sheet) {
let authors: Vec<String> = x.child("authors").map(|a| a.kids("author").map(|a| a.text.clone()).collect()).unwrap_or_default();
let Some(list) = x.child("commentList") else { return };
for c in list.kids("comment") {
let Some(cell) = c.attr("ref").and_then(CellRef::parse) else { continue };
let author = c.attr_u32("authorId").and_then(|i| authors.get(i as usize)).cloned().unwrap_or_default();
let mut text = c.child("text").map(xml::rich_text).unwrap_or_default();
// Excel starts a note with a bold "Author:" line.
if !author.is_empty()
&& let Some(rest) = text.strip_prefix(&format!("{author}:"))
{
text = rest.strip_prefix('\n').unwrap_or(rest).to_string();
}
sheet
.comments
.insert(cell, Comment { author, text, replies: vec![], threaded: false, resolved: false, visible: false, dates: vec![], note_box: None });
}
}
/// Reads the notes' VML shapes: a shape carrying `<x:Visible/>` marks its note as shown, and its
/// `<x:Anchor>` and style size become the note's box. Shapes may sit in groups.
pub(super) fn read_note_shapes(x: &El, sheet: &mut Sheet, depth: usize) {
if depth > xml::MAX_DEPTH {
return;
}
for e in &x.children {
if e.name != "shape" {
read_note_shapes(e, sheet, depth + 1);
continue;
}
let Some(cd) = e.child("ClientData").filter(|cd| cd.attr("ObjectType") == Some("Note")) else { continue };
let num = |k: &str| cd.child(k).and_then(|v| v.text.trim().parse::<u32>().ok());
let (Some(row), Some(col)) = (num("Row"), num("Column")) else { continue };
let cell = CellRef::new(row, col);
let Some(c) = sheet.comments.get_mut(&cell) else { continue };
if cd.child("Visible").is_some() && !c.threaded {
c.visible = true;
}
if let Some(anchor) = cd.child("Anchor") {
c.note_box = note_box(&anchor.text, e.attr("style").unwrap_or(""), cell).filter(|b| *b != crate::sheet_write::DEFAULT_NOTE_BOX);
}
}
}
/// A note's box from its VML `<x:Anchor>` (`LeftColumn, LeftOffset, TopRow, TopOffset,
/// RightColumn, RightOffset, BottomRow, BottomOffset`; offsets in pixels) and its shape's style,
/// the corners made relative to the note's `cell`. `None` when the anchor isn't eight in-sheet
/// numbers.
fn note_box(anchor: &str, style: &str, cell: CellRef) -> Option<NoteBox> {
let v: Vec<u32> = anchor.split(',').map(|p| p.trim().parse::<u32>().ok()).collect::<Option<_>>()?;
let [c1, dx1, r1, dy1, c2, dx2, r2, dy2] = <[u32; 8]>::try_from(v).ok()?;
if c1.max(c2) >= MAX_COLS || r1.max(r2) >= MAX_ROWS {
return None;
}
let corner = |c: u32, dx: u32, r: u32, dy: u32| NoteCorner {
col: i64::from(c) - i64::from(cell.col),
col_px: dx,
row: i64::from(r) - i64::from(cell.row),
row_px: dy,
};
let pt = |key: &str| {
style
.split(';')
.filter_map(|d| d.split_once(':'))
.find(|(k, _)| k.trim().eq_ignore_ascii_case(key))
.and_then(|(_, v)| v.trim().strip_suffix("pt")?.trim().parse::<f64>().ok().filter(|n| n.is_finite() && *n > 0.0 && *n < 1e6))
};
Some(NoteBox { from: corner(c1, dx1, r1, dy1), to: corner(c2, dx2, r2, dy2), size_pt: pt("width").zip(pt("height")) })
}
pub(super) fn read_threaded(cx: &Ctx<'_>, x: &El, sheet: &mut Sheet) {
let mut by_id: HashMap<String, CellRef> = HashMap::new();
let mut replies: Vec<(String, String, String, String)> = vec![];
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -475,7 +475,8 @@ fn the_plain_text_stand_in_for_an_equation_is_drawn_at_a_normal_size() {
// the same box as its fallback. Neither takes the (large) size the equation is drawn at.
let wb = book(vec![equation(1, "B2", "\\begin{CD} A @>f>> B \\end{CD}", Color::Auto), equation(2, "B8", "x^2", Color::Auto)]);
let d = drawing(&unzip(&write_xlsx(&wb).unwrap()));
let text_runs: Vec<&str> = d.match_indices("<a:r><a:rPr").map(|(i, _)| &d[i..i + d[i..].find("</a:rPr>").unwrap()]).collect();
let text_runs: Vec<&str> =
d.match_indices("<a:r><a:rPr").map(|(i, _)| &d[i..i + d[i..].find("</a:rPr>").or_else(|| d[i..].find("/>")).unwrap()]).collect();
assert_eq!(text_runs.len(), 2, "{d}");
for r in text_runs {
assert!(r.contains(" sz=\"1100\""), "{r}");
+41
View File
@@ -883,3 +883,44 @@ fn inline_dxf_number_formats_are_shared() {
assert_eq!(read.dxfs[0].num_fmt.as_str(), code);
assert!(read.dxfs.iter().all(|d| std::sync::Arc::ptr_eq(&d.num_fmt.0, &read.dxfs[0].num_fmt.0)));
}
#[test]
fn two_column_groups_on_different_axes_preserve_secondary_and_kind() {
let drawing = r#"<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<xdr:twoCellAnchor><xdr:from><xdr:col>0</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>0</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from><xdr:to><xdr:col>6</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>15</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:to><xdr:graphicFrame><xdr:nvGraphicFramePr><xdr:cNvPr id="2" name="Chart 1"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/chart"><c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" r:id="rId1"/></a:graphicData></a:graphic></xdr:graphicFrame><xdr:clientData/></xdr:twoCellAnchor>
</xdr:wsDr>"#;
let chart = r#"<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><c:chart><c:plotArea>
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:tx><c:v>Primary</c:v></c:tx><c:val><c:numRef><c:f>Data!$B$2:$B$5</c:f></c:numRef></c:val></c:ser><c:axId val="1"/><c:axId val="2"/></c:barChart>
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="1"/><c:tx><c:v>Secondary</c:v></c:tx><c:val><c:numRef><c:f>Data!$C$2:$C$5</c:f></c:numRef></c:val></c:ser><c:axId val="3"/><c:axId val="4"/></c:barChart>
<c:catAx><c:axId val="1"/></c:catAx><c:valAx><c:axId val="2"/></c:valAx><c:catAx><c:axId val="3"/></c:catAx><c:valAx><c:axId val="4"/></c:valAx>
</c:plotArea></c:chart></c:chartSpace>"#;
let drels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart" Target="../charts/chart1.xml"/></Relationships>"#;
let srels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing1.xml"/></Relationships>"#;
let bytes = minimal(
r#"<sheetData/><drawing r:id="rId1"/>"#,
&[
("xl/worksheets/_rels/sheet1.xml.rels", srels),
("xl/drawings/drawing1.xml", drawing),
("xl/drawings/_rels/drawing1.xml.rels", drels),
("xl/charts/chart1.xml", chart),
],
"",
"",
);
let (wb, _) = read_xlsx(&bytes).unwrap();
let ch = &wb.sheet(0).unwrap().charts[0];
assert_eq!(ch.kind, gridcraft_model::ChartKind::Combo);
assert!(!ch.series[0].secondary);
assert!(ch.series[1].secondary);
assert_eq!(ch.series[0].kind, Some(gridcraft_model::ChartKind::ColumnClustered));
assert_eq!(ch.series[1].kind, Some(gridcraft_model::ChartKind::ColumnClustered));
let out = crate::write_xlsx(&wb).unwrap();
let (wb2, _) = read_xlsx(&out).unwrap();
let ch2 = &wb2.sheet(0).unwrap().charts[0];
assert_eq!(ch2.kind, gridcraft_model::ChartKind::Combo);
assert!(!ch2.series[0].secondary);
assert!(ch2.series[1].secondary);
assert_eq!(ch2.series[0].kind, Some(gridcraft_model::ChartKind::ColumnClustered));
assert_eq!(ch2.series[1].kind, Some(gridcraft_model::ChartKind::ColumnClustered));
}
+82
View File
@@ -2213,3 +2213,85 @@ fn remove_personal_information_is_kept_and_honoured() {
assert_eq!(book.child("workbookPr").and_then(|p| p.attr("filterPrivacy")), None);
assert!(String::from_utf8(pkg.read("docProps/core.xml").unwrap().unwrap()).unwrap().contains("Jane Example"));
}
#[test]
fn issue_778_xlsx_xml_import_save_reopen_roundtrip() {
let mut wb = Workbook::new();
let mut s = Sheet::new("Delegated");
s.cells.set(at("A1"), Cell { value: Value::text("Item"), formula: None, style: StyleId::DEFAULT, py: None });
s.cells.set(at("B1"), Cell { value: Value::text("Amount"), formula: None, style: StyleId::DEFAULT, py: None });
s.cells.set(at("A2"), Cell { value: Value::text("Alpha"), formula: None, style: StyleId::DEFAULT, py: None });
s.cells.set(at("B2"), Cell { value: Value::Number(42.5), formula: None, style: StyleId::DEFAULT, py: None });
let mut f = Cell::formula(Formula::new("=B2*2"));
f.value = Value::Number(85.0);
s.cells.set(at("B3"), f);
s.merges.push(rr("A4:B4"));
s.hyperlinks.insert(at("A2"), Hyperlink { target: "https://example.com".into(), tooltip: Some("Example".into()), external: true });
s.comments.insert(
at("B2"),
Comment {
author: "Reviewer".into(),
text: "Checked".into(),
replies: vec![],
threaded: false,
resolved: false,
visible: true,
dates: vec![],
note_box: None,
},
);
s.shapes.push(Shape {
id: 1,
kind: ShapeKind::Rectangle,
anchor: Anchor { cell: at("D2"), dx: 4.0, dy: 4.0, width: 120.0, height: 60.0, mode: AnchorMode::MoveAndSize },
fill: Color::Rgb(0x336699),
line: Color::Rgb(0x112233),
text: "Box".into(),
format: Default::default(),
rotation: 0.0,
math: Default::default(),
});
s.charts.push(Chart {
id: 2,
kind: ChartKind::ColumnClustered,
anchor: Anchor { cell: at("D6"), dx: 0.0, dy: 0.0, width: 320.0, height: 200.0, mode: AnchorMode::MoveAndSize },
title: Some("Sales".into()),
series: vec![Series {
name: Some("Delegated!$B$1".into()),
categories: Some("Delegated!$A$2:$A$2".into()),
values: "Delegated!$B$2:$B$2".into(),
..Default::default()
}],
legend: LegendPos::Bottom,
data_labels: true,
data_table: Some(ChartDataTable::default()),
gridlines: true,
style: 2,
hole_size: 75,
first_slice_angle: 0,
x_title: None,
y_title: None,
source: None,
by_rows: false,
pivot: None,
});
wb.sheets[0] = Arc::new(s);
let bytes = write_xlsx(&wb).unwrap();
let (reopened, _) = read_xlsx(&bytes).unwrap();
let bytes2 = write_xlsx(&reopened).unwrap();
let (again, _) = read_xlsx(&bytes2).unwrap();
let sh = &again.sheets[0];
assert_eq!(sh.cells.get(at("A2")).unwrap().value, Value::text("Alpha"));
assert_eq!(sh.cells.get(at("B3")).unwrap().value, Value::Number(85.0));
assert_eq!(sh.cells.get(at("B3")).unwrap().formula.as_ref().map(|f| f.text.as_str()), Some("B2*2"));
assert_eq!(sh.merges, vec![rr("A4:B4")]);
assert_eq!(sh.hyperlinks.get(&at("A2")).map(|h| h.target.as_str()), Some("https://example.com"));
assert_eq!(sh.comments.get(&at("B2")).map(|c| c.text.as_str()), Some("Checked"));
assert_eq!(sh.shapes.len(), 1);
assert_eq!(sh.shapes[0].text, "Box");
assert_eq!(sh.charts.len(), 1);
assert_eq!(sh.charts[0].title.as_deref(), Some("Sales"));
assert_eq!(sh.charts[0].data_table, Some(ChartDataTable::default()));
}
+2 -1
View File
@@ -384,7 +384,8 @@ pub fn push_u64(o: &mut String, mut n: u64) {
}
/// Appends the `A1`-style text of `c` ([`gridcraft_core::CellRef::a1`]).
pub fn push_a1(o: &mut String, c: gridcraft_core::CellRef) {
#[cfg(test)]
fn push_a1(o: &mut String, c: gridcraft_core::CellRef) {
let mut letters = [0u8; 8];
let mut i = letters.len();
let mut n = u64::from(c.col) + 1;