Creating and saving an xlsx file

Creating a Workbook struct instance to represent an Excel xlsx file is done via the Workbook::new() method:

// SPDX-License-Identifier: MIT OR Apache-2.0
//
// Copyright 2022-2024, John McNamara, jmcnamara@cpan.org

//! The following example demonstrates creating a simple workbook, with one
//! unused worksheet.

use rust_xlsxwriter::{Workbook, XlsxError};

fn main() -> Result<(), XlsxError> {
    let mut workbook = Workbook::new();

    let _worksheet = workbook.add_worksheet();

    workbook.save("workbook.xlsx")?;

    Ok(())
}

Once you are finished writing data via a worksheet you can save it with the Workbook::save() method:

// SPDX-License-Identifier: MIT OR Apache-2.0
//
// Copyright 2022-2024, John McNamara, jmcnamara@cpan.org

//! The following example demonstrates creating a simple workbook, with one
//! unused worksheet.

use rust_xlsxwriter::{Workbook, XlsxError};

fn main() -> Result<(), XlsxError> {
    let mut workbook = Workbook::new();

    let _worksheet = workbook.add_worksheet();

    workbook.save("workbook.xlsx")?;

    Ok(())
}

This will you a simple output file like the following.

Image of output from doc_workbook_new.rs

The save() method takes a std::path or path/filename string. You can also save the xlsx file data to a Vec<u8> buffer via the Workbook::save_to_buffer() method:

// SPDX-License-Identifier: MIT OR Apache-2.0
//
// Copyright 2022-2024, John McNamara, jmcnamara@cpan.org

//! The following example demonstrates creating a simple workbook to a Vec<u8>
//! buffer.

use rust_xlsxwriter::{Workbook, XlsxError};

fn main() -> Result<(), XlsxError> {
    let mut workbook = Workbook::new();

    let worksheet = workbook.add_worksheet();
    worksheet.write_string(0, 0, "Hello")?;

    let buf = workbook.save_to_buffer()?;

    println!("File size: {}", buf.len());

    Ok(())
}

This can be useful if you intend to stream the data.