Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ criterion = { version = "0.7", features = ["html_reports"] }
name = "basic"
harness = false

[[bench]]
name = "style"
harness = false

[[bench]]
name = "conditional_formatting"
harness = false

# Example that requires the `picture` feature.
[[example]]
name = "read_picture_data"
Expand Down
196 changes: 196 additions & 0 deletions benches/conditional_formatting.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
// SPDX-License-Identifier: MIT
//
// Copyright 2016-2025, Johann Tuffe.

//! Benchmarks for conditional formatting parsing.
//!
//! Run with:
//! ```bash
//! cargo bench --bench conditional_formatting
//! ```

use calamine::{open_workbook, open_workbook_from_rs, Xlsx};
use criterion::{criterion_group, criterion_main, Criterion};
use std::fs::File;
use std::hint::black_box;
use std::io::{BufReader, Cursor, Write};
use zip::write::SimpleFileOptions;
use zip::ZipWriter;

const SMALL_FILE: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/conditional_formatting.xlsx"
);

fn build_large_cf_xlsx() -> Vec<u8> {
let mut buf = Vec::new();
let mut zip = ZipWriter::new(Cursor::new(&mut buf));
let opts = SimpleFileOptions::default();

zip.start_file("[Content_Types].xml", opts).unwrap();
write!(
zip,
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
</Types>"#
)
.unwrap();

zip.start_file("_rels/.rels", opts).unwrap();
write!(
zip,
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
</Relationships>"#
)
.unwrap();

zip.start_file("xl/_rels/workbook.xml.rels", opts).unwrap();
write!(
zip,
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
</Relationships>"#
)
.unwrap();

zip.start_file("xl/workbook.xml", opts).unwrap();
write!(
zip,
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets>
</workbook>"#
)
.unwrap();

zip.start_file("xl/styles.xml", opts).unwrap();
let mut styles = String::from(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts>
<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>
<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>
<cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellXfs>
<dxfs count="100">"#,
);
for i in 0u8..100 {
let r = i.wrapping_mul(37);
let g = i.wrapping_mul(73);
let b = i.wrapping_mul(131);
styles.push_str(&format!(
r#"<dxf><font><color rgb="FF{r:02X}{g:02X}{b:02X}"/><b/></font></dxf>"#
));
}
styles.push_str("</dxfs></styleSheet>");
write!(zip, "{styles}").unwrap();

zip.start_file("xl/worksheets/sheet1.xml", opts).unwrap();
let mut sheet = String::from(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData><row r="1"><c r="A1" t="n"><v>1</v></c></row></sheetData>"#,
);

// 200 CF blocks, each with 5 rules -> 1000 rules total
for block in 0u32..200 {
let row_start = block * 10 + 1;
let row_end = row_start + 9;
let priority_base = block * 5 + 1;
let dxf = (block % 100) as u8;
sheet.push_str(&format!(
r#"<conditionalFormatting sqref="A{row_start}:Z{row_end}">"#
));

sheet.push_str(&format!(
r#"<cfRule type="cellIs" dxfId="{dxf}" priority="{}" operator="greaterThan"><formula>50</formula></cfRule>"#,
priority_base
));
sheet.push_str(&format!(
r#"<cfRule type="colorScale" priority="{}"><colorScale><cfvo type="min"/><cfvo type="max"/><color rgb="FFFF0000"/><color rgb="FF00FF00"/></colorScale></cfRule>"#,
priority_base + 1
));
sheet.push_str(&format!(
r#"<cfRule type="dataBar" priority="{}"><dataBar><cfvo type="min"/><cfvo type="max"/><color rgb="FF638EC6"/></dataBar></cfRule>"#,
priority_base + 2
));
sheet.push_str(&format!(
r#"<cfRule type="iconSet" priority="{}"><iconSet iconSet="3TrafficLights"><cfvo type="percent" val="0"/><cfvo type="percent" val="33"/><cfvo type="percent" val="67"/></iconSet></cfRule>"#,
priority_base + 3
));
sheet.push_str(&format!(
r#"<cfRule type="containsText" dxfId="{}" priority="{}" operator="containsText" text="test"><formula>NOT(ISERROR(SEARCH("test",A{row_start})))</formula></cfRule>"#,
(dxf + 1) % 100,
priority_base + 4
));

sheet.push_str("</conditionalFormatting>");
}

sheet.push_str("</worksheet>");
write!(zip, "{sheet}").unwrap();

zip.finish().unwrap();
buf
}

fn bench_cf_small(c: &mut Criterion) {
c.bench_function("cf_small_25_blocks", |b| {
b.iter(|| {
let mut wb: Xlsx<BufReader<File>> =
open_workbook(SMALL_FILE).expect("cannot open file");
black_box(wb.worksheet_conditional_formatting("Sheet1").unwrap())
})
});
}

fn bench_cf_large(c: &mut Criterion) {
let bytes = build_large_cf_xlsx();

c.bench_function("cf_large_200_blocks_1000_rules", |b| {
b.iter(|| {
let cursor = Cursor::new(&bytes);
let mut wb: Xlsx<Cursor<&Vec<u8>>> =
open_workbook_from_rs(cursor).expect("cannot open file");
black_box(wb.worksheet_conditional_formatting("Sheet1").unwrap())
})
});
}

fn bench_cf_dxf_resolution(c: &mut Criterion) {
let bytes = build_large_cf_xlsx();

c.bench_function("cf_large_with_dxf_access", |b| {
b.iter(|| {
let cursor = Cursor::new(&bytes);
let mut wb: Xlsx<Cursor<&Vec<u8>>> =
open_workbook_from_rs(cursor).expect("cannot open file");
let cfs = wb.worksheet_conditional_formatting("Sheet1").unwrap();
let mut format_count = 0usize;
for cf in &cfs {
for rule in &cf.rules {
if rule.format.is_some() {
format_count += 1;
}
}
}
black_box(format_count)
})
});
}

criterion_group!(
benches,
bench_cf_small,
bench_cf_large,
bench_cf_dxf_resolution
);
criterion_main!(benches);
140 changes: 140 additions & 0 deletions benches/style.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// SPDX-License-Identifier: MIT
//
// Copyright 2016-2025, Johann Tuffe.

//! Benchmarks for style parsing and extraction features.
//!
//! Uses `tests/styles_1M.xlsx` (1M styled cells) for realistic performance
//! measurement.
//!
//! ## Run benchmarks
//!
//! ```bash
//! cargo bench --bench style
//! ```
//!
//! ## Profiling (identify bottlenecks)
//!
//! Install samply (cross-platform, works on macOS and Linux):
//! ```bash
//! cargo install samply
//! ```
//!
//! Profile a specific benchmark:
//! ```bash
//! samply record cargo bench --bench style -- "style/worksheet_style" --profile-time 5
//! ```
//!
//! This opens Firefox Profiler with an interactive flamegraph showing where time is spent.

use calamine::{open_workbook, Reader, Xlsx};
use criterion::{criterion_group, criterion_main, Criterion, SamplingMode};
use std::fs::File;
use std::hint::black_box;
use std::io::BufReader;
use std::time::Duration;

const LARGE_FILE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/styles_1M.xlsx");

fn configure(c: &mut Criterion) -> criterion::BenchmarkGroup<'_, criterion::measurement::WallTime> {
let mut group = c.benchmark_group("style");
group.sample_size(10);
group.warm_up_time(Duration::from_millis(100));
group.measurement_time(Duration::from_secs(15)); // Accommodate slowest benchmark (~1.2s × 10)
group.sampling_mode(SamplingMode::Flat); // 1 iteration per sample for slow benchmarks
group
}

fn bench_style_parsing(c: &mut Criterion) {
if !std::path::Path::new(LARGE_FILE).exists() {
eprintln!("ERROR: tests/styles_1M.xlsx not found.");
return;
}

let mut group = configure(c);

// Core style parsing
group.bench_function("worksheet_style", |b| {
b.iter(|| {
let mut excel: Xlsx<BufReader<File>> =
open_workbook(LARGE_FILE).expect("cannot open file");
black_box(excel.worksheet_style("Sheet 1").unwrap())
})
});

// Layout parsing (column widths, row heights)
group.bench_function("worksheet_layout", |b| {
b.iter(|| {
let mut excel: Xlsx<BufReader<File>> =
open_workbook(LARGE_FILE).expect("cannot open file");
black_box(excel.worksheet_layout("Sheet 1").unwrap())
})
});

// Range parsing (cell values only, no styles)
group.bench_function("worksheet_range", |b| {
b.iter(|| {
let mut excel: Xlsx<BufReader<File>> =
open_workbook(LARGE_FILE).expect("cannot open file");
black_box(excel.worksheet_range("Sheet 1").unwrap())
})
});

// Combined range + style (common real-world usage)
group.bench_function("range_and_style", |b| {
b.iter(|| {
let mut excel: Xlsx<BufReader<File>> =
open_workbook(LARGE_FILE).expect("cannot open file");
let range = excel.worksheet_range("Sheet 1").unwrap();
let style = excel.worksheet_style("Sheet 1").unwrap();
black_box((range.cells().count(), style.cells().count()))
})
});

// Cell-by-cell iteration via cells_reader
group.bench_function("cells_reader", |b| {
b.iter(|| {
let mut excel: Xlsx<BufReader<File>> =
open_workbook(LARGE_FILE).expect("cannot open file");
let mut reader = excel.worksheet_cells_reader("Sheet 1").unwrap();
let mut count = 0usize;
while let Ok(Some(_)) = reader.next_cell() {
count += 1;
}
black_box(count)
})
});

// Iterate and access ALL style properties
group.bench_function("iterate_all_properties", |b| {
b.iter(|| {
let mut excel: Xlsx<BufReader<File>> =
open_workbook(LARGE_FILE).expect("cannot open file");
let styles = excel.worksheet_style("Sheet 1").unwrap();
let mut count = 0usize;
for (_, _, style) in styles.cells() {
if style.get_font().is_some() {
count += 1;
}
if style.get_fill().is_some() {
count += 1;
}
if style.borders.is_some() {
count += 1;
}
if style.get_alignment().is_some() {
count += 1;
}
if style.get_number_format().is_some() {
count += 1;
}
}
black_box(count)
})
});

group.finish();
}

criterion_group!(benches, bench_style_parsing);
criterion_main!(benches);
6 changes: 6 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ This directory contains some example of Calamine usage.
- `read_hyperlinks.rs`: Reads the hyperlinks defined in an XLSX worksheet,
either by sheet name or by sheet index.
- `read_picture_data.rs`: Reads pictures and their metadata from an XLSX file.
- `read_row_and_column_dimensions.rs`: Reads the column widths and row heights
(the worksheet layout) from an XLSX file.
- `read_charts.rs`: Reads the charts embedded in an XLSX worksheet (chart
types, titles, series data, formatting and 3D view settings).
- `conditional_formatting.rs`: Reads the conditional formatting rules defined
in an XLSX worksheet.

### Serialization examples

Expand Down
Loading