tutorial2/
tutorial2.rs

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