Skip to main content

hello_world_xlsx/
hello_world_xlsx.rs

1//! The simplest possible Excel workbook: one sheet, one cell, saved to a
2//! real `.xlsx` file, then read back to prove the file this crate wrote is
3//! valid and round-trips correctly.
4//!
5//! Run with: `cargo run -p office-toolkit --example hello_world_xlsx`
6
7use std::path::{Path, PathBuf};
8
9use office_toolkit::excel::{CellValue, Sheet};
10use office_toolkit::prelude::*;
11use office_toolkit::{OpenFile, SaveToFile};
12
13fn main() -> office_toolkit::Result<()> {
14    let path = output_path("hello_world.xlsx");
15
16    // `Workbook` and `Row` both come from `office_toolkit::prelude`.
17    // `Row::with_text` puts a single text cell in column A.
18    let workbook = Workbook::new()
19        .with_sheet(Sheet::new("Sheet1").with_row(Row::new().with_text("Hello, world!")));
20    workbook.save_to_file(&path)?;
21    println!("Wrote {}", path.display());
22
23    // Read the file back to confirm it is a valid .xlsx.
24    let reopened = Workbook::open_file(&path)?;
25    let cell_a1 = &reopened.sheets[0].rows[0].cells[0].value;
26    println!("Read back A1: {cell_a1:?}");
27    assert!(matches!(cell_a1, CellValue::Text(text) if text == "Hello, world!"));
28
29    Ok(())
30}
31
32/// Every example in this directory writes its output under
33/// `tests-data/output/`, resolved relative to this crate's own manifest so
34/// it works no matter what directory `cargo run` was invoked from.
35fn output_path(filename: &str) -> PathBuf {
36    Path::new(env!("CARGO_MANIFEST_DIR"))
37        .join("../../tests-data/output")
38        .join(filename)
39}