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
//! Excel Table (ListObject) support.
//!
//! This module provides structures for creating and managing Excel Tables,
//! which provide structured references, auto-filtering, and formatting.

/// Table style preset names.
#[derive(Clone, Debug, PartialEq)]
pub enum TableStyle {
    /// No style
    None,
    /// Light style 1-21
    Light(u32),
    /// Medium style 1-28
    Medium(u32),
    /// Dark style 1-11
    Dark(u32),
    /// Custom style name
    Custom(String),
}

impl TableStyle {
    /// Get the style name for XML.
    pub fn style_name(&self) -> String {
        match self {
            TableStyle::None => "TableStyleMedium2".to_string(),
            TableStyle::Light(n) => format!("TableStyleLight{}", n.clamp(&1, &21)),
            TableStyle::Medium(n) => format!("TableStyleMedium{}", n.clamp(&1, &28)),
            TableStyle::Dark(n) => format!("TableStyleDark{}", n.clamp(&1, &11)),
            TableStyle::Custom(name) => name.clone(),
        }
    }

    /// Common presets.
    pub fn blue() -> Self {
        TableStyle::Medium(2)
    }

    pub fn green() -> Self {
        TableStyle::Medium(7)
    }

    pub fn red() -> Self {
        TableStyle::Medium(3)
    }

    pub fn gray() -> Self {
        TableStyle::Medium(1)
    }
}

impl Default for TableStyle {
    fn default() -> Self {
        TableStyle::Medium(2)
    }
}

/// Totals row function for a column.
#[derive(Clone, Debug, PartialEq)]
pub enum TotalsRowFunction {
    /// No function
    None,
    /// Average
    Average,
    /// Count
    Count,
    /// Count numbers
    CountNums,
    /// Maximum
    Max,
    /// Minimum
    Min,
    /// Standard deviation
    StdDev,
    /// Sum
    Sum,
    /// Variance
    Var,
    /// Custom formula
    Custom(String),
}

impl TotalsRowFunction {
    /// Get the XML function name.
    pub fn xml_name(&self) -> Option<&str> {
        match self {
            TotalsRowFunction::None => None,
            TotalsRowFunction::Average => Some("average"),
            TotalsRowFunction::Count => Some("count"),
            TotalsRowFunction::CountNums => Some("countNums"),
            TotalsRowFunction::Max => Some("max"),
            TotalsRowFunction::Min => Some("min"),
            TotalsRowFunction::StdDev => Some("stdDev"),
            TotalsRowFunction::Sum => Some("sum"),
            TotalsRowFunction::Var => Some("var"),
            TotalsRowFunction::Custom(_) => Some("custom"),
        }
    }
}

/// A column in an Excel Table.
#[derive(Clone, Debug)]
pub struct TableColumn {
    /// Column ID (1-based).
    pub id: u32,
    /// Column name/header.
    pub name: String,
    /// Totals row function.
    pub totals_row_function: TotalsRowFunction,
    /// Totals row label (if no function).
    pub totals_row_label: Option<String>,
    /// Column formula (for calculated columns).
    pub calculated_column_formula: Option<String>,
}

impl TableColumn {
    /// Create a new table column.
    pub fn new(id: u32, name: &str) -> Self {
        TableColumn {
            id,
            name: name.to_string(),
            totals_row_function: TotalsRowFunction::None,
            totals_row_label: None,
            calculated_column_formula: None,
        }
    }

    /// Set the totals row function.
    pub fn with_totals_function(mut self, function: TotalsRowFunction) -> Self {
        self.totals_row_function = function;
        self
    }

    /// Set the totals row label.
    pub fn with_totals_label<S: Into<String>>(mut self, label: S) -> Self {
        self.totals_row_label = Some(label.into());
        self
    }

    /// Set a calculated column formula.
    pub fn with_formula<S: Into<String>>(mut self, formula: S) -> Self {
        self.calculated_column_formula = Some(formula.into());
        self
    }
}

/// An Excel Table (ListObject).
#[derive(Clone, Debug)]
pub struct Table {
    /// Table ID (unique within workbook).
    pub id: u32,
    /// Table name (unique within workbook).
    pub name: String,
    /// Display name.
    pub display_name: String,
    /// Cell range reference (e.g., "A1:D10").
    pub range: String,
    /// Table columns.
    pub columns: Vec<TableColumn>,
    /// Table style.
    pub style: TableStyle,
    /// Show header row.
    pub header_row: bool,
    /// Show totals row.
    pub totals_row: bool,
    /// Show first column formatting.
    pub show_first_column: bool,
    /// Show last column formatting.
    pub show_last_column: bool,
    /// Show row stripes.
    pub show_row_stripes: bool,
    /// Show column stripes.
    pub show_column_stripes: bool,
    /// AutoFilter enabled.
    pub auto_filter: bool,
    /// Comment/description.
    pub comment: Option<String>,
}

impl Table {
    /// Create a new table.
    pub fn new(id: u32, name: &str, range: &str) -> Self {
        Table {
            id,
            name: name.to_string(),
            display_name: name.to_string(),
            range: range.to_string(),
            columns: Vec::new(),
            style: TableStyle::default(),
            header_row: true,
            totals_row: false,
            show_first_column: false,
            show_last_column: false,
            show_row_stripes: true,
            show_column_stripes: false,
            auto_filter: true,
            comment: None,
        }
    }

    /// Create a table with auto-generated columns from header names.
    pub fn with_headers(id: u32, name: &str, range: &str, headers: &[&str]) -> Self {
        let mut table = Self::new(id, name, range);
        for (i, header) in headers.iter().enumerate() {
            table.columns.push(TableColumn::new((i + 1) as u32, header));
        }
        table
    }

    /// Set the table style.
    pub fn with_style(mut self, style: TableStyle) -> Self {
        self.style = style;
        self
    }

    /// Enable totals row.
    pub fn with_totals_row(mut self) -> Self {
        self.totals_row = true;
        self
    }

    /// Disable header row.
    pub fn without_header_row(mut self) -> Self {
        self.header_row = false;
        self
    }

    /// Set first column highlighting.
    pub fn with_first_column(mut self) -> Self {
        self.show_first_column = true;
        self
    }

    /// Set last column highlighting.
    pub fn with_last_column(mut self) -> Self {
        self.show_last_column = true;
        self
    }

    /// Enable column stripes instead of row stripes.
    pub fn with_column_stripes(mut self) -> Self {
        self.show_row_stripes = false;
        self.show_column_stripes = true;
        self
    }

    /// Disable auto-filter.
    pub fn without_auto_filter(mut self) -> Self {
        self.auto_filter = false;
        self
    }

    /// Add a column.
    pub fn add_column(&mut self, column: TableColumn) {
        self.columns.push(column);
    }

    /// Set totals function for a column by name.
    pub fn set_column_totals(&mut self, column_name: &str, function: TotalsRowFunction) {
        for col in &mut self.columns {
            if col.name == column_name {
                col.totals_row_function = function;
                break;
            }
        }
    }

    /// Get a structured reference for the table.
    pub fn structured_ref(&self, column: Option<&str>, specifier: Option<&str>) -> String {
        let mut ref_str = format!("{}[", self.name);

        if let Some(spec) = specifier {
            ref_str.push_str(&format!("[{}]", spec));
        }

        if let Some(col) = column {
            if specifier.is_some() {
                ref_str.push(',');
            }
            ref_str.push_str(&format!("[{}]", col));
        }

        ref_str.push(']');
        ref_str
    }
}

/// Structured reference specifiers.
pub mod specifiers {
    /// All data (no headers or totals).
    pub const DATA: &str = "#Data";
    /// Headers row only.
    pub const HEADERS: &str = "#Headers";
    /// Totals row only.
    pub const TOTALS: &str = "#Totals";
    /// All including headers and totals.
    pub const ALL: &str = "#All";
    /// Current row (for formulas within table).
    pub const THIS_ROW: &str = "#This Row";
}

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

    #[test]
    fn test_table_creation() {
        let table = Table::new(1, "SalesData", "A1:D100");
        assert_eq!(table.name, "SalesData");
        assert_eq!(table.range, "A1:D100");
        assert!(table.header_row);
        assert!(!table.totals_row);
    }

    #[test]
    fn test_table_with_headers() {
        let table = Table::with_headers(1, "Products", "A1:C10", &["Name", "Price", "Quantity"]);

        assert_eq!(table.columns.len(), 3);
        assert_eq!(table.columns[0].name, "Name");
        assert_eq!(table.columns[1].name, "Price");
    }

    #[test]
    fn test_table_style() {
        let table = Table::new(1, "Test", "A1:B10").with_style(TableStyle::blue());
        assert_eq!(table.style.style_name(), "TableStyleMedium2");
    }

    #[test]
    fn test_table_totals() {
        let mut table = Table::with_headers(1, "Data", "A1:B10", &["Item", "Value"]);
        table = table.with_totals_row();
        table.set_column_totals("Value", TotalsRowFunction::Sum);

        assert!(table.totals_row);
        assert_eq!(table.columns[1].totals_row_function, TotalsRowFunction::Sum);
    }

    #[test]
    fn test_structured_reference() {
        let table = Table::new(1, "Sales", "A1:C10");

        assert_eq!(
            table.structured_ref(Some("Amount"), None),
            "Sales[[Amount]]"
        );
        assert_eq!(
            table.structured_ref(Some("Amount"), Some("#Data")),
            "Sales[[#Data],[Amount]]"
        );
        assert_eq!(
            table.structured_ref(None, Some("#Totals")),
            "Sales[[#Totals]]"
        );
    }

    #[test]
    fn test_table_column_formula() {
        let col = TableColumn::new(1, "Total").with_formula("[@Price]*[@Quantity]");

        assert_eq!(
            col.calculated_column_formula,
            Some("[@Price]*[@Quantity]".to_string())
        );
    }
}

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

    #[test]
    fn table_style_presets() {
        assert!(!TableStyle::blue().style_name().is_empty());
        assert!(!TableStyle::green().style_name().is_empty());
        assert!(!TableStyle::red().style_name().is_empty());
        assert!(!TableStyle::gray().style_name().is_empty());
    }

    #[test]
    fn totals_functions_xml() {
        assert_eq!(TotalsRowFunction::None.xml_name(), None);
        assert_eq!(TotalsRowFunction::Sum.xml_name(), Some("sum"));
        assert_eq!(TotalsRowFunction::Average.xml_name(), Some("average"));
        assert_eq!(TotalsRowFunction::CountNums.xml_name(), Some("countNums"));
    }

    #[test]
    fn table_column_builders() {
        let c = TableColumn::new(1, "Amount")
            .with_totals_function(TotalsRowFunction::Sum)
            .with_totals_label("Total")
            .with_formula("[Amount]*2");
        assert_eq!(c.id, 1);
        assert_eq!(c.name, "Amount");
    }

    #[test]
    fn table_builders_and_structured_ref() {
        let t = Table::new(1, "Sales", "A1:C10")
            .with_style(TableStyle::blue())
            .with_totals_row()
            .with_first_column()
            .with_last_column()
            .with_column_stripes()
            .without_auto_filter();
        assert_eq!(t.name, "Sales");
        assert!(t.totals_row);
        assert!(!t.auto_filter, "without_auto_filter clears it");

        let h = Table::with_headers(2, "T2", "A1:B5", &["Name", "Value"]).without_header_row();
        assert_eq!(h.columns.len(), 2);

        let mut t3 = Table::new(3, "T3", "A1:B3");
        t3.add_column(TableColumn::new(1, "X"));
        t3.set_column_totals("X", TotalsRowFunction::Count);

        // structured references wrap the table name.
        let sref = t.structured_ref(Some("Sales"), None);
        assert!(sref.contains("Sales"));
    }
}