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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! Page setup and print settings for Excel worksheets.
//!
//! This module provides structures for configuring print layout, margins,
//! headers, footers, and other page setup options.

/// Paper size constants.
#[derive(Clone, Debug, PartialEq, Default)]
pub enum PaperSize {
    /// Letter (8.5" x 11")
    #[default]
    Letter,
    /// Legal (8.5" x 14")
    Legal,
    /// Executive (7.25" x 10.5")
    Executive,
    /// A3 (297mm x 420mm)
    A3,
    /// A4 (210mm x 297mm)
    A4,
    /// A5 (148mm x 210mm)
    A5,
    /// B4 (250mm x 353mm)
    B4,
    /// B5 (182mm x 257mm)
    B5,
    /// Tabloid (11" x 17")
    Tabloid,
    /// Custom size
    Custom(u32),
}

impl PaperSize {
    /// Get the numeric code for this paper size.
    pub fn code(&self) -> u32 {
        match self {
            PaperSize::Letter => 1,
            PaperSize::Legal => 5,
            PaperSize::Executive => 7,
            PaperSize::A3 => 8,
            PaperSize::A4 => 9,
            PaperSize::A5 => 11,
            PaperSize::B4 => 12,
            PaperSize::B5 => 13,
            PaperSize::Tabloid => 3,
            PaperSize::Custom(code) => *code,
        }
    }

    /// Resolve a numeric paperSize attribute back to a variant.
    pub fn from_code(code: u32) -> Self {
        match code {
            1 => PaperSize::Letter,
            3 => PaperSize::Tabloid,
            5 => PaperSize::Legal,
            7 => PaperSize::Executive,
            8 => PaperSize::A3,
            9 => PaperSize::A4,
            11 => PaperSize::A5,
            12 => PaperSize::B4,
            13 => PaperSize::B5,
            other => PaperSize::Custom(other),
        }
    }
}

/// Page orientation.
#[derive(Clone, Debug, PartialEq, Default)]
pub enum Orientation {
    /// Portrait (vertical)
    #[default]
    Portrait,
    /// Landscape (horizontal)
    Landscape,
}

/// Page order for printing.
#[derive(Clone, Debug, PartialEq, Default)]
pub enum PageOrder {
    /// Down then over (default)
    #[default]
    DownThenOver,
    /// Over then down
    OverThenDown,
}

/// Cell comments printing option.
#[derive(Clone, Debug, PartialEq, Default)]
pub enum CellComments {
    /// Don't print comments
    #[default]
    None,
    /// Print at end of sheet
    AtEnd,
    /// Print as displayed
    AsDisplayed,
}

/// Print errors option.
#[derive(Clone, Debug, PartialEq, Default)]
pub enum PrintErrors {
    /// Print as displayed
    #[default]
    Displayed,
    /// Print as blank
    Blank,
    /// Print as dashes
    Dash,
    /// Print as N/A
    NA,
}

/// Page margins in inches.
#[derive(Clone, Debug)]
pub struct PageMargins {
    /// Left margin
    pub left: f64,
    /// Right margin
    pub right: f64,
    /// Top margin
    pub top: f64,
    /// Bottom margin
    pub bottom: f64,
    /// Header margin
    pub header: f64,
    /// Footer margin
    pub footer: f64,
}

impl Default for PageMargins {
    fn default() -> Self {
        PageMargins {
            left: 0.7,
            right: 0.7,
            top: 0.75,
            bottom: 0.75,
            header: 0.3,
            footer: 0.3,
        }
    }
}

impl PageMargins {
    /// Create margins with all values the same.
    pub fn uniform(margin: f64) -> Self {
        PageMargins {
            left: margin,
            right: margin,
            top: margin,
            bottom: margin,
            header: margin / 2.0,
            footer: margin / 2.0,
        }
    }

    /// Narrow margins preset.
    pub fn narrow() -> Self {
        PageMargins {
            left: 0.25,
            right: 0.25,
            top: 0.75,
            bottom: 0.75,
            header: 0.3,
            footer: 0.3,
        }
    }

    /// Wide margins preset.
    pub fn wide() -> Self {
        PageMargins {
            left: 1.0,
            right: 1.0,
            top: 1.0,
            bottom: 1.0,
            header: 0.5,
            footer: 0.5,
        }
    }
}

/// Header or footer section.
#[derive(Clone, Debug, Default)]
pub struct HeaderFooterSection {
    /// Left section content
    pub left: Option<String>,
    /// Center section content
    pub center: Option<String>,
    /// Right section content
    pub right: Option<String>,
}

impl HeaderFooterSection {
    /// Parse a header/footer string with &L/&C/&R section codes back into
    /// sections. Text before any code belongs to the center section, per
    /// Excel's convention.
    pub fn parse_encoded(encoded: &str) -> Self {
        let mut section = HeaderFooterSection::default();
        let mut target: u8 = b'C';
        let mut current = String::new();
        let mut chars = encoded.chars().peekable();

        let flush = |target: u8, text: &mut String, section: &mut HeaderFooterSection| {
            if !text.is_empty() {
                let value = Some(std::mem::take(text));
                match target {
                    b'L' => section.left = value,
                    b'R' => section.right = value,
                    _ => section.center = value,
                }
            }
        };

        while let Some(c) = chars.next() {
            if c == '&' {
                match chars.peek() {
                    Some('L') | Some('C') | Some('R') => {
                        flush(target, &mut current, &mut section);
                        target = *chars.peek().unwrap() as u8;
                        chars.next();
                        continue;
                    }
                    Some('&') => {
                        // && is an escaped literal ampersand
                        current.push('&');
                        chars.next();
                        continue;
                    }
                    _ => {}
                }
            }
            current.push(c);
        }
        flush(target, &mut current, &mut section);
        section
    }

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

    /// Set the left content.
    pub fn with_left<S: Into<String>>(mut self, text: S) -> Self {
        self.left = Some(text.into());
        self
    }

    /// Set the center content.
    pub fn with_center<S: Into<String>>(mut self, text: S) -> Self {
        self.center = Some(text.into());
        self
    }

    /// Set the right content.
    pub fn with_right<S: Into<String>>(mut self, text: S) -> Self {
        self.right = Some(text.into());
        self
    }
}

/// Builds the header/footer string with section codes.
impl std::fmt::Display for HeaderFooterSection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(ref left) = self.left {
            write!(f, "&L{}", left)?;
        }
        if let Some(ref center) = self.center {
            write!(f, "&C{}", center)?;
        }
        if let Some(ref right) = self.right {
            write!(f, "&R{}", right)?;
        }
        Ok(())
    }
}

/// Header and footer configuration.
#[derive(Clone, Debug, Default)]
pub struct HeaderFooter {
    /// Odd page header
    pub odd_header: Option<HeaderFooterSection>,
    /// Odd page footer
    pub odd_footer: Option<HeaderFooterSection>,
    /// Even page header (when different)
    pub even_header: Option<HeaderFooterSection>,
    /// Even page footer (when different)
    pub even_footer: Option<HeaderFooterSection>,
    /// First page header (when different)
    pub first_header: Option<HeaderFooterSection>,
    /// First page footer (when different)
    pub first_footer: Option<HeaderFooterSection>,
    /// Different odd/even pages
    pub different_odd_even: bool,
    /// Different first page
    pub different_first: bool,
    /// Scale with document
    pub scale_with_doc: bool,
    /// Align with margins
    pub align_with_margins: bool,
}

impl HeaderFooter {
    /// Create new header/footer configuration.
    pub fn new() -> Self {
        HeaderFooter {
            scale_with_doc: true,
            align_with_margins: true,
            ..Default::default()
        }
    }

    /// Set the header for all pages.
    pub fn with_header(mut self, section: HeaderFooterSection) -> Self {
        self.odd_header = Some(section);
        self
    }

    /// Set the footer for all pages.
    pub fn with_footer(mut self, section: HeaderFooterSection) -> Self {
        self.odd_footer = Some(section);
        self
    }
}

/// Common header/footer codes.
pub mod codes {
    /// Current page number
    pub const PAGE_NUMBER: &str = "&P";
    /// Total pages
    pub const TOTAL_PAGES: &str = "&N";
    /// Current date
    pub const DATE: &str = "&D";
    /// Current time
    pub const TIME: &str = "&T";
    /// File path
    pub const FILE_PATH: &str = "&Z";
    /// File name
    pub const FILE_NAME: &str = "&F";
    /// Sheet name
    pub const SHEET_NAME: &str = "&A";
    /// Bold on/off
    pub const BOLD: &str = "&B";
    /// Italic on/off
    pub const ITALIC: &str = "&I";
    /// Underline on/off
    pub const UNDERLINE: &str = "&U";
    /// Strikethrough on/off
    pub const STRIKETHROUGH: &str = "&S";
    /// Font size (e.g., &12)
    pub fn font_size(size: u32) -> String {
        format!("&{}", size)
    }
    /// Font name (e.g., &"Arial")
    pub fn font_name(name: &str) -> String {
        format!("&\"{}\"", name)
    }
}

/// Print titles (rows/columns to repeat).
#[derive(Clone, Debug, Default)]
pub struct PrintTitles {
    /// Rows to repeat at top (e.g., "1:2")
    pub rows: Option<String>,
    /// Columns to repeat at left (e.g., "A:B")
    pub cols: Option<String>,
}

impl PrintTitles {
    /// Set rows to repeat.
    pub fn with_rows<S: Into<String>>(mut self, rows: S) -> Self {
        self.rows = Some(rows.into());
        self
    }

    /// Set columns to repeat.
    pub fn with_cols<S: Into<String>>(mut self, cols: S) -> Self {
        self.cols = Some(cols.into());
        self
    }
}

/// Page setup configuration.
#[derive(Clone, Debug)]
pub struct PageSetup {
    /// Paper size
    pub paper_size: PaperSize,
    /// Page orientation
    pub orientation: Orientation,
    /// Scale (percentage, 10-400)
    pub scale: u32,
    /// Fit to width (pages)
    pub fit_to_width: Option<u32>,
    /// Fit to height (pages)
    pub fit_to_height: Option<u32>,
    /// First page number
    pub first_page_number: Option<u32>,
    /// Page order
    pub page_order: PageOrder,
    /// Print black and white
    pub black_and_white: bool,
    /// Print draft quality
    pub draft: bool,
    /// Print cell comments
    pub cell_comments: CellComments,
    /// Print errors
    pub errors: PrintErrors,
    /// Horizontal DPI
    pub horizontal_dpi: Option<u32>,
    /// Vertical DPI
    pub vertical_dpi: Option<u32>,
    /// Number of copies
    pub copies: u32,
    /// Page margins
    pub margins: PageMargins,
    /// Header and footer
    pub header_footer: HeaderFooter,
    /// Print titles
    pub print_titles: PrintTitles,
    /// Print area
    pub print_area: Option<String>,
    /// Print gridlines
    pub print_gridlines: bool,
    /// Print row/column headings
    pub print_headings: bool,
    /// Center horizontally
    pub center_horizontally: bool,
    /// Center vertically
    pub center_vertically: bool,
}

impl Default for PageSetup {
    fn default() -> Self {
        PageSetup {
            paper_size: PaperSize::default(),
            orientation: Orientation::default(),
            scale: 100,
            fit_to_width: None,
            fit_to_height: None,
            first_page_number: None,
            page_order: PageOrder::default(),
            black_and_white: false,
            draft: false,
            cell_comments: CellComments::default(),
            errors: PrintErrors::default(),
            horizontal_dpi: None,
            vertical_dpi: None,
            copies: 1,
            margins: PageMargins::default(),
            header_footer: HeaderFooter::new(),
            print_titles: PrintTitles::default(),
            print_area: None,
            print_gridlines: false,
            print_headings: false,
            center_horizontally: false,
            center_vertically: false,
        }
    }
}

impl PageSetup {
    /// Create new page setup with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set paper size.
    pub fn with_paper_size(mut self, size: PaperSize) -> Self {
        self.paper_size = size;
        self
    }

    /// Set orientation.
    pub fn with_orientation(mut self, orientation: Orientation) -> Self {
        self.orientation = orientation;
        self
    }

    /// Set scale percentage.
    pub fn with_scale(mut self, scale: u32) -> Self {
        self.scale = scale.clamp(10, 400);
        self
    }

    /// Fit to one page wide.
    pub fn fit_to_page(mut self) -> Self {
        self.fit_to_width = Some(1);
        self.fit_to_height = Some(1);
        self
    }

    /// Fit to width.
    pub fn fit_to_width(mut self, pages: u32) -> Self {
        self.fit_to_width = Some(pages);
        self
    }

    /// Set margins.
    pub fn with_margins(mut self, margins: PageMargins) -> Self {
        self.margins = margins;
        self
    }

    /// Set print area.
    pub fn with_print_area<S: Into<String>>(mut self, area: S) -> Self {
        self.print_area = Some(area.into());
        self
    }

    /// Enable gridline printing.
    pub fn print_gridlines(mut self) -> Self {
        self.print_gridlines = true;
        self
    }

    /// Center on page.
    pub fn center_on_page(mut self) -> Self {
        self.center_horizontally = true;
        self.center_vertically = true;
        self
    }
}

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

    #[test]
    fn test_page_setup_default() {
        let setup = PageSetup::new();
        assert_eq!(setup.paper_size, PaperSize::Letter);
        assert_eq!(setup.orientation, Orientation::Portrait);
        assert_eq!(setup.scale, 100);
    }

    #[test]
    fn test_page_setup_builder() {
        let setup = PageSetup::new()
            .with_paper_size(PaperSize::A4)
            .with_orientation(Orientation::Landscape)
            .with_scale(80)
            .print_gridlines()
            .center_on_page();

        assert_eq!(setup.paper_size, PaperSize::A4);
        assert_eq!(setup.orientation, Orientation::Landscape);
        assert_eq!(setup.scale, 80);
        assert!(setup.print_gridlines);
        assert!(setup.center_horizontally);
    }

    #[test]
    fn test_margins() {
        let margins = PageMargins::narrow();
        assert_eq!(margins.left, 0.25);
        assert_eq!(margins.right, 0.25);
    }

    #[test]
    fn test_header_footer_section() {
        let section = HeaderFooterSection::new()
            .with_left("Left text")
            .with_center(format!(
                "Page {} of {}",
                codes::PAGE_NUMBER,
                codes::TOTAL_PAGES
            ))
            .with_right(codes::DATE);

        let s = section.to_string();
        assert!(s.contains("&L"));
        assert!(s.contains("&P"));
        assert!(s.contains("&D"));
    }

    #[test]
    fn test_paper_size_code() {
        assert_eq!(PaperSize::Letter.code(), 1);
        assert_eq!(PaperSize::A4.code(), 9);
    }
}

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

    #[test]
    fn paper_size_code_roundtrip() {
        for size in [
            PaperSize::Letter,
            PaperSize::Legal,
            PaperSize::A3,
            PaperSize::A4,
            PaperSize::A5,
            PaperSize::Tabloid,
        ] {
            let code = size.code();
            assert_eq!(PaperSize::from_code(code), size);
        }
        // Unknown code falls back to a default.
        let _ = PaperSize::from_code(9999);
    }

    #[test]
    fn page_margins_presets() {
        let u = PageMargins::uniform(1.0);
        assert_eq!(u.left, 1.0);
        assert_eq!(u.right, 1.0);
        let _ = PageMargins::narrow();
        let _ = PageMargins::wide();
    }

    #[test]
    fn header_footer_sections() {
        let s = HeaderFooterSection::new()
            .with_left("L")
            .with_center("C")
            .with_right("R");
        assert_eq!(s.left.as_deref(), Some("L"));
        assert_eq!(s.center.as_deref(), Some("C"));
        assert_eq!(s.right.as_deref(), Some("R"));

        // parse_encoded splits an &L..&C..&R.. string back into sections.
        let parsed = HeaderFooterSection::parse_encoded("&LLeft&CCenter&RRight");
        assert_eq!(parsed.left.as_deref(), Some("Left"));
        assert_eq!(parsed.center.as_deref(), Some("Center"));
        assert_eq!(parsed.right.as_deref(), Some("Right"));

        let hf = HeaderFooter::new()
            .with_header(HeaderFooterSection::new().with_center("Title"))
            .with_footer(HeaderFooterSection::new().with_center("Page &P"));
        assert!(hf.odd_header.is_some() && hf.odd_footer.is_some());

        assert!(codes::font_size(12).contains("12"));
        assert!(codes::font_name("Arial").contains("Arial"));
    }

    #[test]
    fn print_titles() {
        let t = PrintTitles::default().with_rows("1:1").with_cols("A:A");
        assert_eq!(t.rows.as_deref(), Some("1:1"));
        assert_eq!(t.cols.as_deref(), Some("A:A"));
    }

    #[test]
    fn page_setup_builders() {
        let ps = PageSetup::new()
            .with_paper_size(PaperSize::A4)
            .with_orientation(Orientation::Landscape)
            .with_scale(90)
            .with_margins(PageMargins::narrow())
            .with_print_area("A1:D20")
            .print_gridlines()
            .center_on_page();
        assert_eq!(ps.orientation, Orientation::Landscape);
        assert_eq!(ps.scale, 90);
        assert_eq!(ps.print_area.as_deref(), Some("A1:D20"));

        let fit = PageSetup::new().fit_to_page().fit_to_width(2);
        assert!(fit.fit_to_width.is_some() || fit.fit_to_height.is_some());
    }
}