rustypyxl 0.7.1

Fast, dependency-light Rust library for reading and writing Excel (XLSX) files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! Chart support for Excel workbooks.
//!
//! This module provides structures for creating and manipulating charts in Excel files.
//!
//! **Status: read + write.** A [`Chart`] added to a worksheet is serialized on save
//! (chart part, drawing, and anchor), so it opens in Excel with the series, labels,
//! title, legend, and axes intact; and charts present in a loaded file are read back
//! into this model, so they survive a load/save round-trip. Supported types: bar,
//! column, line, area, pie, doughnut, and scatter; other types fall back to a bar
//! chart on write. Axis min/max and per-series colors are written but not read back.

use std::collections::HashMap;

/// Type of chart.
#[derive(Clone, Debug, PartialEq)]
pub enum ChartType {
    /// Bar chart (horizontal bars).
    Bar,
    /// Column chart (vertical bars).
    Column,
    /// Line chart.
    Line,
    /// Pie chart.
    Pie,
    /// Doughnut chart.
    Doughnut,
    /// Area chart.
    Area,
    /// Scatter/XY chart.
    Scatter,
    /// Radar chart.
    Radar,
    /// Stock chart.
    Stock,
    /// Surface chart.
    Surface,
    /// Bubble chart.
    Bubble,
}

impl ChartType {
    /// Get the XML type name for this chart type.
    pub fn xml_type(&self) -> &'static str {
        match self {
            ChartType::Bar => "barChart",
            ChartType::Column => "barChart",
            ChartType::Line => "lineChart",
            ChartType::Pie => "pieChart",
            ChartType::Doughnut => "doughnutChart",
            ChartType::Area => "areaChart",
            ChartType::Scatter => "scatterChart",
            ChartType::Radar => "radarChart",
            ChartType::Stock => "stockChart",
            ChartType::Surface => "surfaceChart",
            ChartType::Bubble => "bubbleChart",
        }
    }
}

/// Grouping style for bar/column charts.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum BarGrouping {
    /// Clustered (side by side).
    #[default]
    Clustered,
    /// Stacked.
    Stacked,
    /// 100% stacked.
    PercentStacked,
}

/// Direction for bar charts.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum BarDirection {
    /// Horizontal bars.
    Bar,
    /// Vertical bars (columns).
    #[default]
    Col,
}

/// A data series in a chart.
#[derive(Clone, Debug)]
pub struct ChartSeries {
    /// Series name/title.
    pub name: Option<String>,
    /// Reference to category (X axis) data, e.g., "Sheet1!$A$2:$A$10".
    pub categories: Option<String>,
    /// Reference to values (Y axis) data, e.g., "Sheet1!$B$2:$B$10".
    pub values: String,
    /// Fill color for the series.
    pub fill_color: Option<String>,
    /// Line color for the series.
    pub line_color: Option<String>,
    /// Marker style for line/scatter charts.
    pub marker_style: Option<String>,
}

impl ChartSeries {
    /// Create a new series with values reference.
    pub fn new<S: Into<String>>(values: S) -> Self {
        ChartSeries {
            name: None,
            categories: None,
            values: values.into(),
            fill_color: None,
            line_color: None,
            marker_style: None,
        }
    }

    /// Set the series name.
    pub fn with_name<S: Into<String>>(mut self, name: S) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the categories reference.
    pub fn with_categories<S: Into<String>>(mut self, categories: S) -> Self {
        self.categories = Some(categories.into());
        self
    }

    /// Set the fill color.
    pub fn with_fill_color<S: Into<String>>(mut self, color: S) -> Self {
        self.fill_color = Some(color.into());
        self
    }
}

/// Chart axis configuration.
#[derive(Clone, Debug, Default)]
pub struct ChartAxis {
    /// Axis title.
    pub title: Option<String>,
    /// Minimum value (None for auto).
    pub min_val: Option<f64>,
    /// Maximum value (None for auto).
    pub max_val: Option<f64>,
    /// Major unit/interval.
    pub major_unit: Option<f64>,
    /// Minor unit/interval.
    pub minor_unit: Option<f64>,
    /// Number format for axis labels.
    pub number_format: Option<String>,
    /// Whether to show gridlines.
    pub gridlines: bool,
    /// Position: "b" (bottom), "l" (left), "t" (top), "r" (right).
    pub position: Option<String>,
}

impl ChartAxis {
    /// Create a new axis.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the axis title.
    pub fn with_title<S: Into<String>>(mut self, title: S) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set min and max values.
    pub fn with_range(mut self, min: f64, max: f64) -> Self {
        self.min_val = Some(min);
        self.max_val = Some(max);
        self
    }
}

/// Chart legend configuration.
#[derive(Clone, Debug, Default)]
pub struct ChartLegend {
    /// Legend position: "b" (bottom), "l" (left), "t" (top), "r" (right), "tr" (top-right).
    pub position: String,
    /// Whether to show the legend.
    pub visible: bool,
}

impl ChartLegend {
    /// Create a new legend.
    pub fn new() -> Self {
        ChartLegend {
            position: "r".to_string(),
            visible: true,
        }
    }

    /// Set the legend position.
    pub fn with_position<S: Into<String>>(mut self, position: S) -> Self {
        self.position = position.into();
        self
    }

    /// Set visibility.
    pub fn with_visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }
}

/// Chart title configuration.
#[derive(Clone, Debug, Default)]
pub struct ChartTitle {
    /// Title text.
    pub text: Option<String>,
    /// Font size.
    pub font_size: Option<f64>,
    /// Font bold.
    pub bold: bool,
}

impl ChartTitle {
    /// Create a new title.
    pub fn new<S: Into<String>>(text: S) -> Self {
        ChartTitle {
            text: Some(text.into()),
            font_size: None,
            bold: false,
        }
    }
}

/// Anchor position for a chart.
#[derive(Clone, Debug)]
pub struct ChartAnchor {
    /// Cell reference for top-left corner.
    pub from_cell: String,
    /// Column offset in EMUs (English Metric Units).
    pub from_col_offset: u32,
    /// Row offset in EMUs.
    pub from_row_offset: u32,
    /// Cell reference for bottom-right corner.
    pub to_cell: Option<String>,
    /// Column offset for bottom-right.
    pub to_col_offset: u32,
    /// Row offset for bottom-right.
    pub to_row_offset: u32,
}

impl ChartAnchor {
    /// Create an anchor at the specified cell.
    pub fn at<S: Into<String>>(cell: S) -> Self {
        ChartAnchor {
            from_cell: cell.into(),
            from_col_offset: 0,
            from_row_offset: 0,
            to_cell: None,
            to_col_offset: 0,
            to_row_offset: 0,
        }
    }

    /// Set the size by specifying the to_cell.
    pub fn with_size<S: Into<String>>(mut self, to_cell: S) -> Self {
        self.to_cell = Some(to_cell.into());
        self
    }
}

/// A chart in an Excel worksheet.
#[derive(Clone, Debug)]
pub struct Chart {
    /// Chart type.
    pub chart_type: ChartType,
    /// Chart title.
    pub title: Option<ChartTitle>,
    /// Data series.
    pub series: Vec<ChartSeries>,
    /// X axis (category axis).
    pub x_axis: Option<ChartAxis>,
    /// Y axis (value axis).
    pub y_axis: Option<ChartAxis>,
    /// Legend configuration.
    pub legend: Option<ChartLegend>,
    /// Position/anchor in the worksheet.
    pub anchor: Option<ChartAnchor>,
    /// Width in EMUs (914400 EMUs = 1 inch).
    pub width: u32,
    /// Height in EMUs.
    pub height: u32,
    /// Bar grouping (for bar/column charts).
    pub bar_grouping: BarGrouping,
    /// Bar direction (for bar/column charts).
    pub bar_direction: BarDirection,
    /// Additional properties.
    pub properties: HashMap<String, String>,
}

impl Chart {
    /// Create a new chart of the specified type.
    pub fn new(chart_type: ChartType) -> Self {
        Chart {
            chart_type,
            title: None,
            series: Vec::new(),
            x_axis: None,
            y_axis: None,
            legend: Some(ChartLegend::new()),
            anchor: None,
            width: 4572000,  // ~5 inches
            height: 2743200, // ~3 inches
            bar_grouping: BarGrouping::default(),
            bar_direction: BarDirection::default(),
            properties: HashMap::new(),
        }
    }

    /// Create a bar chart.
    pub fn bar() -> Self {
        let mut chart = Self::new(ChartType::Bar);
        chart.bar_direction = BarDirection::Bar;
        chart
    }

    /// Create a column chart.
    pub fn column() -> Self {
        let mut chart = Self::new(ChartType::Column);
        chart.bar_direction = BarDirection::Col;
        chart
    }

    /// Create a line chart.
    pub fn line() -> Self {
        Self::new(ChartType::Line)
    }

    /// Create a pie chart.
    pub fn pie() -> Self {
        Self::new(ChartType::Pie)
    }

    /// Create a scatter chart.
    pub fn scatter() -> Self {
        Self::new(ChartType::Scatter)
    }

    /// Create an area chart.
    pub fn area() -> Self {
        Self::new(ChartType::Area)
    }

    /// Set the chart title.
    pub fn with_title<S: Into<String>>(mut self, title: S) -> Self {
        self.title = Some(ChartTitle::new(title));
        self
    }

    /// Add a data series.
    pub fn add_series(&mut self, series: ChartSeries) {
        self.series.push(series);
    }

    /// Set the X axis.
    pub fn with_x_axis(mut self, axis: ChartAxis) -> Self {
        self.x_axis = Some(axis);
        self
    }

    /// Set the Y axis.
    pub fn with_y_axis(mut self, axis: ChartAxis) -> Self {
        self.y_axis = Some(axis);
        self
    }

    /// Set the legend.
    pub fn with_legend(mut self, legend: ChartLegend) -> Self {
        self.legend = Some(legend);
        self
    }

    /// Set the anchor position.
    pub fn with_anchor(mut self, anchor: ChartAnchor) -> Self {
        self.anchor = Some(anchor);
        self
    }

    /// Set the chart size in inches.
    pub fn with_size_inches(mut self, width: f64, height: f64) -> Self {
        // 914400 EMUs per inch
        self.width = (width * 914400.0) as u32;
        self.height = (height * 914400.0) as u32;
        self
    }

    /// Set bar grouping style.
    pub fn with_grouping(mut self, grouping: BarGrouping) -> Self {
        self.bar_grouping = grouping;
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_create_bar_chart() {
        let chart = Chart::bar().with_title("Sales Data");

        assert_eq!(chart.chart_type, ChartType::Bar);
        assert!(chart.title.is_some());
    }

    #[test]
    fn test_create_line_chart() {
        let chart = Chart::line().with_title("Trends");

        assert_eq!(chart.chart_type, ChartType::Line);
    }

    #[test]
    fn test_add_series() {
        let mut chart = Chart::bar();
        chart.add_series(
            ChartSeries::new("Sheet1!$B$2:$B$10")
                .with_name("Revenue")
                .with_categories("Sheet1!$A$2:$A$10"),
        );

        assert_eq!(chart.series.len(), 1);
        assert_eq!(chart.series[0].name, Some("Revenue".to_string()));
    }

    #[test]
    fn test_chart_axes() {
        let chart = Chart::bar()
            .with_x_axis(ChartAxis::new().with_title("Categories"))
            .with_y_axis(ChartAxis::new().with_title("Values").with_range(0.0, 100.0));

        assert!(chart.x_axis.is_some());
        assert!(chart.y_axis.is_some());
        assert_eq!(chart.y_axis.as_ref().unwrap().min_val, Some(0.0));
    }

    #[test]
    fn test_chart_size() {
        let chart = Chart::pie().with_size_inches(6.0, 4.0);

        // 6 inches * 914400 EMUs/inch
        assert_eq!(chart.width, 5486400);
    }

    #[test]
    fn test_chart_type_xml() {
        assert_eq!(ChartType::Bar.xml_type(), "barChart");
        assert_eq!(ChartType::Line.xml_type(), "lineChart");
        assert_eq!(ChartType::Pie.xml_type(), "pieChart");
    }
}

#[cfg(test)]
mod coverage_tests {
    use super::*;

    #[test]
    fn chart_type_xml_names() {
        assert_eq!(ChartType::Column.xml_type(), "barChart");
        assert_eq!(ChartType::Area.xml_type(), "areaChart");
        assert_eq!(ChartType::Doughnut.xml_type(), "doughnutChart");
        assert_eq!(ChartType::Scatter.xml_type(), "scatterChart");
        assert_eq!(ChartType::Radar.xml_type(), "radarChart");
        assert_eq!(ChartType::Bubble.xml_type(), "bubbleChart");
    }

    #[test]
    fn constructors_and_builders() {
        assert_eq!(Chart::area().chart_type, ChartType::Area);
        assert_eq!(Chart::scatter().chart_type, ChartType::Scatter);
        assert_eq!(Chart::pie().chart_type, ChartType::Pie);

        let chart = Chart::column()
            .with_x_axis(ChartAxis::new().with_title("Cats"))
            .with_y_axis(ChartAxis::new().with_title("Vals").with_range(0.0, 50.0))
            .with_grouping(BarGrouping::Stacked)
            .with_size_inches(6.0, 4.0)
            .with_anchor(ChartAnchor::at("B2").with_size("F20"));
        assert!(chart.x_axis.is_some() && chart.y_axis.is_some());
        assert_eq!(chart.bar_grouping, BarGrouping::Stacked);
        assert_eq!(chart.width, 5486400);
        let a = chart.anchor.unwrap();
        assert_eq!(a.from_cell, "B2");
        assert_eq!(a.to_cell.as_deref(), Some("F20"));
    }

    #[test]
    fn axis_range_sets_min_max() {
        let ax = ChartAxis::new().with_range(1.0, 9.0);
        assert_eq!(ax.min_val, Some(1.0));
        assert_eq!(ax.max_val, Some(9.0));
    }

    #[test]
    fn series_with_fill_color() {
        let s = ChartSeries::new("S!$B$1:$B$3")
            .with_name("Rev")
            .with_categories("S!$A$1:$A$3")
            .with_fill_color("FF0000");
        assert_eq!(s.fill_color.as_deref(), Some("FF0000"));
        assert_eq!(s.name.as_deref(), Some("Rev"));
    }

    #[test]
    fn legend_builder() {
        let l = ChartLegend::new().with_position("t").with_visible(false);
        assert_eq!(l.position, "t");
        assert!(!l.visible);
    }
}