tutorial3/
tutorial3.rs

1//! A simple program to write some data to an Excel file.
2
3use chrono::{DateTime, TimeZone, Utc};
4use karo::{index, Format, NumFormat, Workbook};
5
6struct Expense {
7    item: &'static str,
8    cost: f64,
9    datetime: DateTime<Utc>,
10}
11
12fn main() -> karo::Result<()> {
13    let expenses = [
14        Expense {
15            item: "Rent",
16            cost: 1000f64,
17            datetime: Utc.ymd(2013, 1, 13).and_hms(0, 0, 0),
18        },
19        Expense {
20            item: "Gas",
21            cost: 100f64,
22            datetime: Utc.ymd(2013, 1, 14).and_hms(0, 0, 0),
23        },
24        Expense {
25            item: "Food",
26            cost: 300f64,
27            datetime: Utc.ymd(2013, 1, 16).and_hms(0, 0, 0),
28        },
29        Expense {
30            item: "Gym",
31            cost: 50f64,
32            datetime: Utc.ymd(2013, 1, 20).and_hms(0, 0, 0),
33        },
34    ];
35
36    // Create a new workbook.
37    let mut workbook = Workbook::new();
38
39    {
40        // Add a worksheet with a user defined name.
41        let worksheet = workbook.add_worksheet(None)?;
42
43        // Add a bold format to use to highlight cells.
44        let mut bold = Format::default();
45        bold.font.bold = true;
46
47        // Add a number format for cells with money.
48        let mut money = Format::default();
49        money.num_format = NumFormat::from_format_string("$#,##0");
50
51        // Add a number format for cells with money.
52        let mut date = Format::default();
53        date.num_format = NumFormat::from_format_string("mmmm d yyyy");
54
55        let mut row = 0u32;
56
57        worksheet.write_string(index(row, 0)?, "Item", Some(&bold))?;
58        worksheet.write_string(index(row, 1)?, "Cost", Some(&bold))?;
59        row += 1;
60
61        for Expense {
62            item,
63            cost,
64            datetime,
65        } in expenses.iter()
66        {
67            worksheet.write_string(index(row, 0)?, item, None)?;
68            worksheet.write_datetime(
69                index(row, 1)?,
70                *datetime,
71                Some(&date),
72            )?;
73            worksheet.write_number(index(row, 2)?, *cost, Some(&money))?;
74            row += 1;
75        }
76
77        worksheet.write_string(index(row, 0)?, "Total", Some(&bold))?;
78        worksheet.write_formula(
79            index(row, 2)?,
80            "=SUM(C2:C5)",
81            Some(&money),
82        )?;
83    }
84
85    workbook.write_file("tutorial03.xlsx")?;
86
87    Ok(())
88}