Skip to main content

format_num_format/
format_num_format.rs

1//! Example of writing some data with numeric formatting to a simple
2//! Excel file.
3
4use karo::{col_range, index, Format, NumFormat, Workbook};
5
6fn main() -> karo::Result<()> {
7    // Create a new workbook.
8    let mut workbook = Workbook::new();
9
10    {
11        let worksheet = workbook.add_worksheet(None)?;
12
13        // Widen the first column to make the text clearer.
14        worksheet.set_column(col_range(0, 0)?, 30f64, None)?;
15
16        let mut f = Format::default();
17
18        // 3.1415926
19        worksheet.write_number(index(0, 0)?, 3.1415926, None)?;
20
21        // 3.142
22        f.num_format = NumFormat::from_format_string("0.000");
23        worksheet.write_number(index(1, 0)?, 3.1415926, Some(&f))?;
24
25        // 1,235
26        f.num_format = NumFormat::from_format_string("#,##0");
27        worksheet.write_number(index(2, 0)?, 1234.56, Some(&f))?;
28
29        // 1,234.56
30        f.num_format = NumFormat::from_format_string("#,##0.00");
31        worksheet.write_number(index(3, 0)?, 1234.56, Some(&f))?;
32
33        // 49.99
34        f.num_format = NumFormat::from_format_string("0.00");
35        worksheet.write_number(index(4, 0)?, 49.99, Some(&f))?;
36
37        // 01/01/01
38        f.num_format = NumFormat::from_format_string("mm/dd/yy");
39        worksheet.write_number(index(5, 0)?, 36892.521, Some(&f))?;
40
41        // Jan 1 2001
42        f.num_format = NumFormat::from_format_string("mmm d yyyy");
43        worksheet.write_number(index(6, 0)?, 36892.521, Some(&f))?;
44
45        // 1 January 2001
46        f.num_format = NumFormat::from_format_string("d mmmm yyyy");
47        worksheet.write_number(index(7, 0)?, 36892.521, Some(&f))?;
48
49        // 01/01/2001 12:30 AM
50        f.num_format =
51            NumFormat::from_format_string("dd/mm/yyyy hh:mm AM/PM");
52        worksheet.write_number(index(8, 0)?, 36892.521, Some(&f))?;
53
54        // 1 dollar and .87 cents
55        f.num_format = NumFormat::from_format_string(
56            "0 \"dollar and\" .00 \"cents\"",
57        );
58        worksheet.write_number(index(9, 0)?, 1.87, Some(&f))?;
59
60        // Show limited conditional number formats.
61        f.num_format = NumFormat::from_format_string(
62            "[Green]General;[Red]-General;General",
63        );
64        worksheet.write_number(index(10, 0)?, 123.0, Some(&f))?; // > 0 Green
65        worksheet.write_number(index(11, 0)?, -45.0, Some(&f))?; // < 0 Red
66        worksheet.write_number(index(12, 0)?, 0.0, Some(&f))?; // = 0 Default color
67
68        // Format a Zip code
69        f.num_format = NumFormat::from_format_string("00000");
70        worksheet.write_number(index(13, 0)?, 1209.0, Some(&f))?;
71    }
72
73    workbook.write_file("format_num_format.xlsx")?;
74
75    Ok(())
76}