Calamine Library for Rust: Reading Excel Files
1. What Is Calamine and Why Use It
Calamine is a high-performance Rust library for reading Excel files (formats .xlsx, .xls, .xlsb, .ods). Written entirely in pure Rust with zero external dependencies, it's an ideal choice for projects where speed, memory safety, and cross-platform compatibility matter. Unlike many other libraries, Calamine requires neither Microsoft Office nor a Java Runtime Environment.
Calamine's primary purpose is extracting data from spreadsheets. It supports reading cells, rows, columns, sheets, and working with formulas, dates, numbers, and strings. The library is especially useful for automating report processing, importing Excel data into databases, analyzing large tables, and building ETL data pipelines.
Designed with performance in mind, Calamine uses streaming reads and lazy data loading, allowing you to process files hundreds of megabytes in size without significant memory consumption. The library is actively maintained by the Rust community and is used in well-known projects like rust-xlsxwriter and tauri.
2. Installation
To add Calamine to your Rust project, run this command in your terminal:
cargo add calamine
Or manually add the dependency to your Cargo.toml file:
[dependencies]
calamine = "0.24"
Then run cargo build to download and compile the library. Make sure you have Rust installed (version 1.65+ recommended).
3. Quick Start
A minimal example of reading data from an Excel file:
use calamine::{open_workbook, Reader, Xlsx};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Open the file
let mut workbook: Xlsx<_> = open_workbook("data.xlsx")?;
// Get the first sheet
let sheet_name = workbook.sheet_names()[0].clone();
let range = workbook.worksheet_range(&sheet_name)?;
// Print the contents
for row in range.rows() {
for cell in row {
print!("{:?}\t", cell);
}
println!();
}
Ok(())
}
This code opens data.xlsx, reads the first sheet, and prints all cells to the console. Note the use of open_workbook — a universal function for opening files in any supported format.
4. Key Methods and Functions
4.1. open_workbook
Signature: pub fn open_workbook<P: AsRef<Path>, T: Reader<BufReader<File>>>(path: P) -> Result<T, CalamineError>
What it does: Opens an Excel file at the specified path and returns a workbook of the specified type. The return type depends on the file format: Xlsx, Xls, Xlsb, or Ods.
use calamine::{open_workbook, Xlsx};
fn main() {
let mut workbook: Xlsx<_> = open_workbook("report.xlsx").expect("Cannot open file");
println!("File opened successfully");
}
4.2. sheet_names
Signature: fn sheet_names(&a