laravel-excel 0.3.0

Excel, CSV, ODS, HTML and PDF exports and imports with typed columns for Laravel Rust: a port of Laravel Excel (maatwebsite/excel).
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
//! Cell styles: the subset of PhpSpreadsheet's `Style::applyFromArray()` that Laravel Excel's
//! `WithStyles`, `WithDefaultStyles`, `WithBackgroundColor` and `WithColumnFormatting` use.

use serde::{Deserialize, Serialize};

/// A style to apply to cells, rows or columns. Every unset part leaves the cell's current style
/// alone, as `applyFromArray()` does.
///
/// ```
/// use laravel_excel::style::{Horizontal, Style};
///
/// let heading = Style::new().bold().font_size(14.0).background("FFFF00").horizontal(Horizontal::Center);
/// ```
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Style {
    /// The font.
    #[serde(default)]
    pub font: Font,
    /// The solid fill color, as `RRGGBB` or `AARRGGBB` hex.
    #[serde(default)]
    pub fill: Option<String>,
    /// The alignment.
    #[serde(default)]
    pub alignment: Alignment,
    /// The borders.
    #[serde(default)]
    pub borders: Borders,
    /// The number format code, such as `0.00` or `dd/mm/yyyy`.
    #[serde(default)]
    pub number_format: Option<String>,
}

/// A style's font.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Font {
    /// Bold text.
    pub bold: Option<bool>,
    /// Italic text.
    pub italic: Option<bool>,
    /// Underlined text.
    pub underline: Option<bool>,
    /// Struck through text.
    pub strikethrough: Option<bool>,
    /// The font size in points.
    pub size: Option<f64>,
    /// The font name, such as `Arial`.
    pub name: Option<String>,
    /// The font color, as `RRGGBB` or `AARRGGBB` hex.
    pub color: Option<String>,
}

/// Horizontal alignment: PhpSpreadsheet's `Alignment::HORIZONTAL_*`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Horizontal {
    /// `general`.
    General,
    /// `left`.
    Left,
    /// `right`.
    Right,
    /// `center`.
    Center,
    /// `centerContinuous`.
    CenterContinuous,
    /// `justify`.
    Justify,
    /// `fill`.
    Fill,
    /// `distributed`.
    Distributed,
}

/// Vertical alignment: PhpSpreadsheet's `Alignment::VERTICAL_*`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Vertical {
    /// `bottom`.
    Bottom,
    /// `top`.
    Top,
    /// `center`.
    Center,
    /// `justify`.
    Justify,
    /// `distributed`.
    Distributed,
}

/// A style's alignment.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Alignment {
    /// Horizontal alignment.
    pub horizontal: Option<Horizontal>,
    /// Vertical alignment.
    pub vertical: Option<Vertical>,
    /// Wrap the text.
    pub wrap_text: Option<bool>,
    /// The indent level.
    pub indent: Option<u8>,
    /// The text rotation in degrees, from -90 to 90.
    pub text_rotation: Option<i16>,
}

/// A border's line style: PhpSpreadsheet's `Border::BORDER_*`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BorderStyle {
    /// `none`.
    None,
    /// `thin`.
    Thin,
    /// `medium`.
    Medium,
    /// `thick`.
    Thick,
    /// `dashed`.
    Dashed,
    /// `dotted`.
    Dotted,
    /// `double`.
    Double,
    /// `hair`.
    Hair,
    /// `mediumDashed`.
    MediumDashed,
    /// `dashDot`.
    DashDot,
    /// `mediumDashDot`.
    MediumDashDot,
    /// `dashDotDot`.
    DashDotDot,
    /// `mediumDashDotDot`.
    MediumDashDotDot,
    /// `slantDashDot`.
    SlantDashDot,
}

/// One border of a cell.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Border {
    /// The line style.
    pub style: BorderStyle,
    /// The color, as `RRGGBB` hex, or black.
    pub color: Option<String>,
}

/// A cell's borders.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Borders {
    /// The top border.
    pub top: Option<Border>,
    /// The bottom border.
    pub bottom: Option<Border>,
    /// The left border.
    pub left: Option<Border>,
    /// The right border.
    pub right: Option<Border>,
}

macro_rules! merge {
    ($target:expr, $source:expr, $($field:ident),*) => {
        $(
            if $source.$field.is_some() {
                $target.$field = $source.$field.clone();
            }
        )*
    };
}

impl Style {
    /// An empty style, which changes nothing.
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether the style changes nothing.
    pub fn is_empty(&self) -> bool {
        *self == Self::default()
    }

    /// Applies `other` on top of this style: the parts `other` sets replace this style's.
    pub fn apply(&mut self, other: &Style) {
        merge!(
            self.font,
            other.font,
            bold,
            italic,
            underline,
            strikethrough,
            size,
            name,
            color
        );
        merge!(self, other, fill, number_format);
        merge!(
            self.alignment,
            other.alignment,
            horizontal,
            vertical,
            wrap_text,
            indent,
            text_rotation
        );
        merge!(self.borders, other.borders, top, bottom, left, right);
    }

    /// This style with `other` applied on top.
    pub fn merged(&self, other: &Style) -> Style {
        let mut style = self.clone();
        style.apply(other);
        style
    }

    /// Bold text: `['font' => ['bold' => true]]`.
    pub fn bold(mut self) -> Self {
        self.font.bold = Some(true);
        self
    }

    /// Italic text.
    pub fn italic(mut self) -> Self {
        self.font.italic = Some(true);
        self
    }

    /// Underlined text.
    pub fn underline(mut self) -> Self {
        self.font.underline = Some(true);
        self
    }

    /// Struck through text.
    pub fn strikethrough(mut self) -> Self {
        self.font.strikethrough = Some(true);
        self
    }

    /// The font size in points.
    pub fn font_size(mut self, size: f64) -> Self {
        self.font.size = Some(size);
        self
    }

    /// The font name.
    pub fn font_name(mut self, name: impl Into<String>) -> Self {
        self.font.name = Some(name.into());
        self
    }

    /// The font color, as `RRGGBB` or `AARRGGBB` hex.
    pub fn font_color(mut self, color: impl Into<String>) -> Self {
        self.font.color = Some(color.into());
        self
    }

    /// A solid background color, as `RRGGBB` or `AARRGGBB` hex:
    /// `['fill' => ['fillType' => 'solid', 'startColor' => ['argb' => ..]]]`.
    pub fn background(mut self, color: impl Into<String>) -> Self {
        self.fill = Some(color.into());
        self
    }

    /// Horizontal alignment.
    pub fn horizontal(mut self, horizontal: Horizontal) -> Self {
        self.alignment.horizontal = Some(horizontal);
        self
    }

    /// Vertical alignment.
    pub fn vertical(mut self, vertical: Vertical) -> Self {
        self.alignment.vertical = Some(vertical);
        self
    }

    /// Wraps the text.
    pub fn wrap_text(mut self) -> Self {
        self.alignment.wrap_text = Some(true);
        self
    }

    /// The indent level.
    pub fn indent(mut self, indent: u8) -> Self {
        self.alignment.indent = Some(indent);
        self
    }

    /// Rotates the text, in degrees from -90 to 90.
    pub fn text_rotation(mut self, degrees: i16) -> Self {
        self.alignment.text_rotation = Some(degrees);
        self
    }

    /// The same border on all four sides: `['borders' => ['allBorders' => [..]]]`.
    pub fn border(mut self, style: BorderStyle) -> Self {
        let border = Some(Border { style, color: None });
        self.borders = Borders {
            top: border.clone(),
            bottom: border.clone(),
            left: border.clone(),
            right: border,
        };
        self
    }

    /// The same colored border on all four sides.
    pub fn border_with_color(mut self, style: BorderStyle, color: impl Into<String>) -> Self {
        let border = Some(Border {
            style,
            color: Some(color.into()),
        });
        self.borders = Borders {
            top: border.clone(),
            bottom: border.clone(),
            left: border.clone(),
            right: border,
        };
        self
    }

    /// The top border.
    pub fn border_top(mut self, style: BorderStyle) -> Self {
        self.borders.top = Some(Border { style, color: None });
        self
    }

    /// The bottom border.
    pub fn border_bottom(mut self, style: BorderStyle) -> Self {
        self.borders.bottom = Some(Border { style, color: None });
        self
    }

    /// The left border.
    pub fn border_left(mut self, style: BorderStyle) -> Self {
        self.borders.left = Some(Border { style, color: None });
        self
    }

    /// The right border.
    pub fn border_right(mut self, style: BorderStyle) -> Self {
        self.borders.right = Some(Border { style, color: None });
        self
    }

    /// The number format code: `['numberFormat' => ['formatCode' => ..]]`.
    pub fn number_format(mut self, format: impl Into<String>) -> Self {
        self.number_format = Some(format.into());
        self
    }
}

/// Normalizes a hex color to `RRGGBB`, dropping a leading `#` and an alpha channel.
pub(crate) fn rgb(color: &str) -> Option<u32> {
    let hex = color.trim().trim_start_matches('#');
    let hex = if hex.len() == 8 { &hex[2..] } else { hex };
    if hex.len() != 6 {
        return None;
    }
    u32::from_str_radix(hex, 16).ok()
}

/// Number format codes: the `NumberFormat::FORMAT_*` constants of PhpSpreadsheet.
pub mod number_format {
    pub use crate::number_formatter::format_value;

    /// `NumberFormat::FORMAT_GENERAL`.
    pub const FORMAT_GENERAL: &str = "General";
    /// `NumberFormat::FORMAT_TEXT`.
    pub const FORMAT_TEXT: &str = "@";
    /// `NumberFormat::FORMAT_NUMBER`.
    pub const FORMAT_NUMBER: &str = "0";
    /// `NumberFormat::FORMAT_NUMBER_0`.
    pub const FORMAT_NUMBER_0: &str = "0.0";
    /// `NumberFormat::FORMAT_NUMBER_00`.
    pub const FORMAT_NUMBER_00: &str = "0.00";
    /// `NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1`.
    pub const FORMAT_NUMBER_COMMA_SEPARATED1: &str = "#,##0.00";
    /// `NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2`.
    pub const FORMAT_NUMBER_COMMA_SEPARATED2: &str = "#,##0.00_-";
    /// `NumberFormat::FORMAT_PERCENTAGE`.
    pub const FORMAT_PERCENTAGE: &str = "0%";
    /// `NumberFormat::FORMAT_PERCENTAGE_0`.
    pub const FORMAT_PERCENTAGE_0: &str = "0.0%";
    /// `NumberFormat::FORMAT_PERCENTAGE_00`.
    pub const FORMAT_PERCENTAGE_00: &str = "0.00%";
    /// `NumberFormat::FORMAT_DATE_YYYYMMDD`.
    pub const FORMAT_DATE_YYYYMMDD: &str = "yyyy-mm-dd";
    /// `NumberFormat::FORMAT_DATE_DDMMYYYY`.
    pub const FORMAT_DATE_DDMMYYYY: &str = "dd/mm/yyyy";
    /// `NumberFormat::FORMAT_DATE_DMYSLASH`.
    pub const FORMAT_DATE_DMYSLASH: &str = "d/m/yy";
    /// `NumberFormat::FORMAT_DATE_DMYMINUS`.
    pub const FORMAT_DATE_DMYMINUS: &str = "d-m-yy";
    /// `NumberFormat::FORMAT_DATE_DMMINUS`.
    pub const FORMAT_DATE_DMMINUS: &str = "d-m";
    /// `NumberFormat::FORMAT_DATE_MYMINUS`.
    pub const FORMAT_DATE_MYMINUS: &str = "m-yy";
    /// `NumberFormat::FORMAT_DATE_XLSX14`.
    pub const FORMAT_DATE_XLSX14: &str = "mm-dd-yy";
    /// `NumberFormat::FORMAT_DATE_XLSX15`.
    pub const FORMAT_DATE_XLSX15: &str = "d-mmm-yy";
    /// `NumberFormat::FORMAT_DATE_XLSX16`.
    pub const FORMAT_DATE_XLSX16: &str = "d-mmm";
    /// `NumberFormat::FORMAT_DATE_XLSX17`.
    pub const FORMAT_DATE_XLSX17: &str = "mmm-yy";
    /// `NumberFormat::FORMAT_DATE_XLSX22`.
    pub const FORMAT_DATE_XLSX22: &str = "m/d/yy h:mm";
    /// `NumberFormat::FORMAT_DATE_DATETIME`.
    pub const FORMAT_DATE_DATETIME: &str = "d/m/yy h:mm";
    /// `NumberFormat::FORMAT_DATE_TIME1`.
    pub const FORMAT_DATE_TIME1: &str = "h:mm AM/PM";
    /// `NumberFormat::FORMAT_DATE_TIME2`.
    pub const FORMAT_DATE_TIME2: &str = "h:mm:ss AM/PM";
    /// `NumberFormat::FORMAT_DATE_TIME3`.
    pub const FORMAT_DATE_TIME3: &str = "h:mm";
    /// `NumberFormat::FORMAT_DATE_TIME4`.
    pub const FORMAT_DATE_TIME4: &str = "h:mm:ss";
    /// `NumberFormat::FORMAT_DATE_TIME5`.
    pub const FORMAT_DATE_TIME5: &str = "mm:ss";
    /// `NumberFormat::FORMAT_DATE_TIME6`.
    pub const FORMAT_DATE_TIME6: &str = "h:mm:ss";
    /// `NumberFormat::FORMAT_DATE_TIME8`.
    pub const FORMAT_DATE_TIME8: &str = "h:mm:ss;@";
    /// `NumberFormat::FORMAT_DATE_YYYYMMDDSLASH`.
    pub const FORMAT_DATE_YYYYMMDDSLASH: &str = "yyyy/mm/dd;@";
}