mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-22 02:21:28 +01:00
xlsx, drawingml: track dropped cells and chart data tables/pivot source/first slice angle (#778) (#2465)
* xlsx, drawingml: track dropped cells and chart data tables/pivot source/first slice angle (#778) * xlsx, drawingml: add unit tests for dropped_cells, ChartDataTable, first_slice_angle, pivot_source (#778)
This commit is contained in:
1 parent
0275c0b107
commit
0ffb1a0abe
5 files changed
+127
-6
No files matched your search
@@ -344,6 +344,26 @@ impl ErrorBars {
|
||||
}
|
||||
}
|
||||
|
||||
/// A chart's data table (`c:dTable`), independent of the chart legend.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ChartDataTable {
|
||||
pub show_keys: bool,
|
||||
pub horizontal_border: bool,
|
||||
pub vertical_border: bool,
|
||||
pub outline: bool,
|
||||
}
|
||||
|
||||
impl Default for ChartDataTable {
|
||||
fn default() -> Self {
|
||||
Self { show_keys: true, horizontal_border: true, vertical_border: true, outline: true }
|
||||
}
|
||||
}
|
||||
|
||||
fn is_zero_u16(v: &u16) -> bool {
|
||||
*v == 0
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Chart {
|
||||
@@ -423,6 +443,15 @@ pub struct Chart {
|
||||
/// A histogram's bin width (`cx:binSize`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bin_size: Option<f64>,
|
||||
/// A chart's data table (`c:dTable`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub data_table: Option<ChartDataTable>,
|
||||
/// Pie/doughnut first slice angle in degrees clockwise from 12 o'clock (0–359).
|
||||
#[serde(skip_serializing_if = "is_zero_u16")]
|
||||
pub first_slice_angle: u16,
|
||||
/// A PivotChart's PivotTable reference (`c:pivotSource/c:name`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub pivot_source: Option<String>,
|
||||
/// Original chart XML part kept for round-trip of unmodelled options.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub raw: Option<String>,
|
||||
@@ -537,6 +566,9 @@ impl Default for Chart {
|
||||
up_down_bars: false,
|
||||
bin_count: None,
|
||||
bin_size: None,
|
||||
data_table: None,
|
||||
first_slice_angle: 0,
|
||||
pivot_source: None,
|
||||
raw: None,
|
||||
verbatim: false,
|
||||
kept: ChartKept::default(),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Chart parts (`c:chartSpace`) → [`Chart`]. The original XML is kept in `Chart.raw`.
|
||||
|
||||
use crate::chart::{Chart, ChartType, ErrorBars, Series, Trendline, TrendlineType};
|
||||
use crate::chart::{Chart, ChartDataTable, ChartType, ErrorBars, Series, Trendline, TrendlineType};
|
||||
use crate::style::Fill;
|
||||
|
||||
use craft_xml::{El, Local, value};
|
||||
@@ -194,6 +194,16 @@ fn chart_within(root: &El, mut budget: usize) -> Option<Chart> {
|
||||
}
|
||||
}
|
||||
c.lang = root.child(Local("lang")).and_then(|c| c.attr_local("val")).map(str::to_string);
|
||||
c.pivot_source = root.path(&[Local("pivotSource"), Local("name")]).map(|n| n.deep_text().trim().to_string()).filter(|n| !n.is_empty());
|
||||
c.data_table = pa.child(Local("dTable")).map(|t| {
|
||||
let flag = |name: &str| t.child(Local(name)).is_some_and(|e| e.attr_local("val").and_then(value::to_bool).unwrap_or(true));
|
||||
ChartDataTable {
|
||||
show_keys: flag("showKeys"),
|
||||
horizontal_border: flag("showHorzBorder"),
|
||||
vertical_border: flag("showVertBorder"),
|
||||
outline: flag("showOutline"),
|
||||
}
|
||||
});
|
||||
let (val_ax, cat_ax) = read_axes(&mut c, pa, &primary_val);
|
||||
read_text_styles(&mut c, root, ch, val_ax, cat_ax);
|
||||
Some(c)
|
||||
@@ -288,6 +298,9 @@ fn read_group_settings(g: &El, c: &mut Chart) -> Option<bool> {
|
||||
if let Some(v) = g.child(Local("holeSize")).and_then(|c| c.attr_local("val")).and_then(|v| v.parse::<f64>().ok()) {
|
||||
c.hole_size = (v / 100.0).clamp(0.0, 0.9);
|
||||
}
|
||||
if let Some(v) = g.child(Local("firstSliceAng")).and_then(|c| c.attr_local("val")).and_then(|v| v.trim().parse::<u16>().ok()) {
|
||||
c.first_slice_angle = v % 360;
|
||||
}
|
||||
// `<c:showVal/>` without a val attribute means true, as in the schema's default.
|
||||
// The setting belongs to this plot group: a group that asks for no labels keeps them
|
||||
// off, even when another group of a combo chart asks for them (#868).
|
||||
@@ -902,4 +915,30 @@ mod tests {
|
||||
assert!(read_chart_xml(vary_xml(r#"<c:varyColors val="0"/>"#).as_bytes()).is_some_and(|c| !c.vary_colors));
|
||||
assert!(read_chart_xml(vary_xml(r#"<c:varyColors val="1"/>"#).as_bytes()).is_some_and(|c| c.vary_colors));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_table_first_slice_angle_and_pivot_source_roundtrip() {
|
||||
let xml = format!(
|
||||
r#"<c:chartSpace xmlns:c="{NS_C}"><c:pivotSource><c:name>[Book.xlsx]Sheet1!PivotTable1</c:name><c:fmtId val="0"/></c:pivotSource><c:chart><c:plotArea><c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:val><c:numLit><c:ptCount val="1"/><c:pt idx="0"><c:v>5</c:v></c:pt></c:numLit></c:val></c:ser></c:barChart><c:dTable><c:showHorzBorder/><c:showVertBorder val="0"/><c:showOutline val="1"/><c:showKeys/></c:dTable></c:plotArea></c:chart></c:chartSpace>"#
|
||||
);
|
||||
let c = read_chart_xml(xml.as_bytes()).unwrap();
|
||||
assert_eq!(c.pivot_source.as_deref(), Some("[Book.xlsx]Sheet1!PivotTable1"));
|
||||
assert_eq!(c.data_table, Some(ChartDataTable { show_keys: true, horizontal_border: true, vertical_border: false, outline: true }));
|
||||
let mut edited = c.clone();
|
||||
edited.raw = None;
|
||||
let (written, kept) = crate::chart::write::chart_xml(&edited);
|
||||
assert!(!kept);
|
||||
let back = read_chart_xml(&written).unwrap();
|
||||
assert_eq!(back.pivot_source, c.pivot_source);
|
||||
assert_eq!(back.data_table, c.data_table);
|
||||
|
||||
let pie_xml = format!(
|
||||
r#"<c:chartSpace xmlns:c="{NS_C}"><c:chart><c:plotArea><c:pieChart><c:ser><c:idx val="0"/><c:val><c:numLit><c:ptCount val="1"/><c:pt idx="0"><c:v>5</c:v></c:pt></c:numLit></c:val></c:ser><c:firstSliceAng val="450"/></c:pieChart></c:plotArea></c:chart></c:chartSpace>"#
|
||||
);
|
||||
let mut pie = read_chart_xml(pie_xml.as_bytes()).unwrap();
|
||||
assert_eq!(pie.first_slice_angle, 90);
|
||||
pie.raw = None;
|
||||
let (pie_written, _) = crate::chart::write::chart_xml(&pie);
|
||||
assert_eq!(read_chart_xml(&pie_written).unwrap().first_slice_angle, 90);
|
||||
}
|
||||
}
|
||||
@@ -645,9 +645,9 @@ fn plot_group(w: &mut Writer, c: &Chart, kind: ChartType, list: &[(usize, &Serie
|
||||
w.close();
|
||||
}
|
||||
}
|
||||
Group::Pie => w.tag("c:firstSliceAng").attr("val", 0).empty(),
|
||||
Group::Pie => w.tag("c:firstSliceAng").attr("val", c.first_slice_angle % 360).empty(),
|
||||
Group::Doughnut => {
|
||||
w.tag("c:firstSliceAng").attr("val", 0).empty();
|
||||
w.tag("c:firstSliceAng").attr("val", c.first_slice_angle % 360).empty();
|
||||
w.tag("c:holeSize").attr("val", (c.hole_size.clamp(0.1, 0.9) * 100.0).round() as i64).empty();
|
||||
}
|
||||
_ => {}
|
||||
@@ -733,6 +733,12 @@ pub fn chart_xml(c: &Chart) -> (Vec<u8>, bool) {
|
||||
w.tag("c:date1904").attr("val", 0).empty();
|
||||
w.tag("c:roundedCorners").attr("val", 0).empty();
|
||||
w.tag("c:style").attr("val", c.style.clamp(1, 48)).empty();
|
||||
if let Some(pivot) = c.pivot_source.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
|
||||
w.open("c:pivotSource", &[]);
|
||||
w.tag("c:name").text(pivot);
|
||||
w.tag("c:fmtId").attr("val", 0).empty();
|
||||
w.close();
|
||||
}
|
||||
w.open("c:chart", &[]);
|
||||
match &c.title {
|
||||
Some(t) => {
|
||||
@@ -802,6 +808,22 @@ pub fn chart_xml(c: &Chart) -> (Vec<u8>, bool) {
|
||||
axes(&mut w, c, g);
|
||||
}
|
||||
}
|
||||
if let Some(dt) = &c.data_table {
|
||||
w.open("c:dTable", &[]);
|
||||
if dt.horizontal_border {
|
||||
w.empty("c:showHorzBorder", &[]);
|
||||
}
|
||||
if dt.vertical_border {
|
||||
w.empty("c:showVertBorder", &[]);
|
||||
}
|
||||
if dt.outline {
|
||||
w.empty("c:showOutline", &[]);
|
||||
}
|
||||
if dt.show_keys {
|
||||
w.empty("c:showKeys", &[]);
|
||||
}
|
||||
w.close();
|
||||
}
|
||||
if let Some(f) = &c.plot_fill {
|
||||
sp_pr(&mut w, Some(f), None);
|
||||
}
|
||||
|
||||
@@ -291,8 +291,16 @@ impl<'a> Package<'a> {
|
||||
if rows.dropped > 0 {
|
||||
self.warn(format!("sheet \"{}\": {} cells or rows outside the 1,048,576 × 16,384 grid were dropped", entry.name, rows.dropped));
|
||||
}
|
||||
let mut sheet =
|
||||
SheetPart { part, root: root.unwrap_or_default(), rels, rows: rows.rows, dropped: rows.dropped, damaged, ..SheetPart::default() };
|
||||
let mut sheet = SheetPart {
|
||||
part,
|
||||
root: root.unwrap_or_default(),
|
||||
rels,
|
||||
rows: rows.rows,
|
||||
dropped: rows.dropped,
|
||||
dropped_cells: rows.dropped_cells,
|
||||
damaged,
|
||||
..SheetPart::default()
|
||||
};
|
||||
sheet.lift();
|
||||
Ok(sheet)
|
||||
}
|
||||
|
||||
@@ -190,6 +190,8 @@ pub struct SheetPart {
|
||||
pub rows: u64,
|
||||
/// Rows and cells dropped because their position was outside the grid or unreadable.
|
||||
pub dropped: u64,
|
||||
/// Cell elements (`<c>`) inside dropped rows or dropped for an invalid/out-of-grid reference.
|
||||
pub dropped_cells: u64,
|
||||
/// Why reading stopped early, when the part is damaged; the rows before the damage were
|
||||
/// handed out.
|
||||
pub damaged: Option<String>,
|
||||
@@ -361,6 +363,7 @@ pub(crate) struct RowReader {
|
||||
next_row: u32,
|
||||
pub(crate) rows: u64,
|
||||
pub(crate) dropped: u64,
|
||||
pub(crate) dropped_cells: u64,
|
||||
}
|
||||
|
||||
impl RowReader {
|
||||
@@ -371,11 +374,13 @@ impl RowReader {
|
||||
Some(r) if (1..=MAX_ROWS).contains(&r) => r - 1,
|
||||
Some(_) => {
|
||||
self.dropped += 1;
|
||||
self.dropped_cells += e.children("c").count() as u64;
|
||||
return None;
|
||||
}
|
||||
None if self.next_row < MAX_ROWS => self.next_row,
|
||||
None => {
|
||||
self.dropped += 1;
|
||||
self.dropped_cells += e.children("c").count() as u64;
|
||||
return None;
|
||||
}
|
||||
};
|
||||
@@ -398,12 +403,14 @@ impl RowReader {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
self.dropped += 1;
|
||||
self.dropped_cells += 1;
|
||||
continue;
|
||||
}
|
||||
},
|
||||
None if next_col < MAX_COLS => CellRef::new(index, next_col),
|
||||
None => {
|
||||
self.dropped += 1;
|
||||
self.dropped_cells += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
@@ -569,7 +576,20 @@ mod tests {
|
||||
assert_eq!(next, Some(3));
|
||||
assert!(r.row(&craft_xml::El::new("row").with_attr("r", "1048577")).is_none());
|
||||
assert!(r.row(&craft_xml::El::new("row").with_attr("r", "0")).is_none());
|
||||
assert_eq!((r.rows, r.dropped), (4, 3));
|
||||
assert_eq!((r.rows, r.dropped, r.dropped_cells), (4, 3, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropped_cells_counts_cells_in_dropped_rows_and_bad_refs() {
|
||||
let mut r = RowReader::default();
|
||||
let bad_row_zero = craft_xml::Options::local().parse(br#"<row r="0"><c><v>1</v></c><c><v>2</v></c></row>"#).unwrap();
|
||||
let bad_row_high = craft_xml::Options::local().parse(br#"<row r="1048577"><c r="A1048577"><v>3</v></c></row>"#).unwrap();
|
||||
let bad_cell = craft_xml::Options::local().parse(br#"<row r="1"><c r="XFE1"><v>4</v></c><c r="A1"><v>5</v></c></row>"#).unwrap();
|
||||
assert!(r.row(&bad_row_zero).is_none());
|
||||
assert!(r.row(&bad_row_high).is_none());
|
||||
let kept = r.row(&bad_cell).unwrap();
|
||||
assert_eq!(kept.cells.len(), 1);
|
||||
assert_eq!((r.dropped, r.dropped_cells), (3, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user