pub mod autofilter;
pub mod chart;
pub mod image;
pub mod pivot;
pub mod protection;
pub mod shape;
pub mod table;
use crate::coordinate::{CellRef, Col, Range, Row};
use crate::error::{CellError, Error, Result};
use crate::shared::date::Epoch;
use crate::style::{Color, DiffFont, StyleId, StyleTable};
use std::collections::BTreeMap;
use std::sync::Arc;
pub use autofilter::{
AutoFilter, ColumnFilter, CustomFilter, DateGroup, FilterColumn, FilterOperator,
};
pub use protection::{PasswordHash, ProtectedRange, SheetProtection, WorkbookProtection};
pub const MAX_STRING_LENGTH: usize = 32_767;
pub const SHEET_TITLE_MAX_LENGTH: usize = 31;
pub const SHEET_TITLE_INVALID_CHARS: [char; 7] = ['*', ':', '/', '\\', '?', '[', ']'];
#[derive(Debug, Clone, PartialEq, Default)]
pub enum CellValue {
#[default]
Empty,
Number(f64),
Text(Arc<str>),
Bool(bool),
Error(CellError),
RichText(Vec<TextRun>),
Formula {
formula: String,
cached: Option<Box<CellValue>>,
},
}
impl CellValue {
#[must_use]
pub fn text(value: impl Into<String>) -> Self {
let s = value.into();
let s = match s.char_indices().nth(MAX_STRING_LENGTH) {
Some((byte_idx, _)) => s[..byte_idx].to_owned(),
None => s,
};
Self::Text(s.into())
}
#[must_use]
pub const fn shared_text(value: Arc<str>) -> Self {
Self::Text(value)
}
#[must_use]
pub const fn is_empty(&self) -> bool {
matches!(self, Self::Empty)
}
#[must_use]
pub fn plain_text(&self) -> Option<String> {
match self {
Self::Text(t) => Some(t.to_string()),
Self::RichText(runs) => Some(runs.iter().map(|r| r.text.as_str()).collect()),
_ => None,
}
}
#[must_use]
pub fn formula(text: impl Into<String>) -> Self {
Self::Formula {
formula: text.into(),
cached: None,
}
}
#[must_use]
pub fn result(&self) -> &Self {
match self {
Self::Formula { cached, .. } => cached.as_deref().unwrap_or(&Self::Empty),
other => other,
}
}
#[must_use]
pub fn as_number(&self) -> Option<f64> {
match self.result() {
Self::Number(n) => Some(*n),
_ => None,
}
}
#[must_use]
pub fn as_str(&self) -> Option<&str> {
match self.result() {
Self::Text(t) => Some(t),
_ => None,
}
}
#[must_use]
pub fn as_bool(&self) -> Option<bool> {
match self.result() {
Self::Bool(b) => Some(*b),
_ => None,
}
}
#[must_use]
pub fn as_error(&self) -> Option<crate::CellError> {
match self.result() {
Self::Error(e) => Some(*e),
_ => None,
}
}
#[must_use]
pub fn display(&self, code: &str, epoch: crate::shared::date::Epoch) -> String {
use crate::style::format::{Value as FormatValue, format};
match self.result() {
Self::Number(n) => format(FormatValue::Number(*n), code, epoch),
Self::Text(t) => format(FormatValue::Text(t), code, epoch),
Self::Bool(b) => (if *b { "TRUE" } else { "FALSE" }).to_owned(),
Self::Error(e) => e.as_str().to_owned(),
Self::RichText(runs) => {
let text: String = runs.iter().map(|r| r.text.as_str()).collect();
format(FormatValue::Text(&text), code, epoch)
}
Self::Empty | Self::Formula { .. } => String::new(),
}
}
}
impl From<f64> for CellValue {
fn from(v: f64) -> Self {
Self::Number(v)
}
}
impl From<i64> for CellValue {
#[expect(
clippy::cast_precision_loss,
reason = "Excel stores every number as f64"
)]
fn from(v: i64) -> Self {
Self::Number(v as f64)
}
}
impl From<bool> for CellValue {
fn from(v: bool) -> Self {
Self::Bool(v)
}
}
impl From<&str> for CellValue {
fn from(v: &str) -> Self {
Self::text(v)
}
}
impl From<String> for CellValue {
fn from(v: String) -> Self {
Self::text(v)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TextRun {
pub text: String,
pub font: Option<DiffFont>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Comment {
pub author: String,
pub text: Vec<TextRun>,
}
impl Comment {
#[must_use]
pub fn plain_text(&self) -> String {
self.text.iter().map(|r| r.text.as_str()).collect()
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Cell {
pub value: CellValue,
pub style: StyleId,
}
impl Cell {
#[must_use]
pub fn new(value: impl Into<CellValue>) -> Self {
Self {
value: value.into(),
style: StyleId::default(),
}
}
}
#[expect(
clippy::struct_excessive_bools,
reason = "these are the independent flags of a <col> element, not a state \
machine that an enum could replace"
)]
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnRun {
pub first: Col,
pub last: Col,
pub width: Option<f64>,
pub custom_width: bool,
pub hidden: bool,
pub best_fit: bool,
pub style: Option<StyleId>,
pub outline_level: u8,
pub collapsed: bool,
}
impl ColumnRun {
#[must_use]
pub fn new(first: Col, last: Col) -> Self {
Self {
first,
last,
width: None,
custom_width: false,
hidden: false,
best_fit: false,
style: None,
outline_level: 0,
collapsed: false,
}
}
#[must_use]
pub fn is_meaningful(&self) -> bool {
self.width.is_some()
|| self.hidden
|| self.best_fit
|| self.style.is_some()
|| self.outline_level > 0
|| self.collapsed
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct RowProperties {
pub height: Option<f64>,
pub custom_height: bool,
pub hidden: bool,
pub style: Option<StyleId>,
pub outline_level: u8,
pub collapsed: bool,
}
impl RowProperties {
#[must_use]
pub fn is_meaningful(&self) -> bool {
self.height.is_some()
|| self.hidden
|| self.style.is_some()
|| self.outline_level > 0
|| self.collapsed
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PanePosition {
#[default]
TopLeft,
TopRight,
BottomLeft,
BottomRight,
}
impl PanePosition {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::TopLeft => "topLeft",
Self::TopRight => "topRight",
Self::BottomLeft => "bottomLeft",
Self::BottomRight => "bottomRight",
}
}
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"topRight" => Self::TopRight,
"bottomLeft" => Self::BottomLeft,
"bottomRight" => Self::BottomRight,
_ => Self::TopLeft,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PaneState {
#[default]
Split,
Frozen,
FrozenSplit,
}
impl PaneState {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Split => "split",
Self::Frozen => "frozen",
Self::FrozenSplit => "frozenSplit",
}
}
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"frozen" => Self::Frozen,
"frozenSplit" => Self::FrozenSplit,
_ => Self::Split,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SheetViewType {
#[default]
Normal,
PageLayout,
PageBreakPreview,
}
impl SheetViewType {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Normal => "normal",
Self::PageLayout => "pageLayout",
Self::PageBreakPreview => "pageBreakPreview",
}
}
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"pageLayout" => Self::PageLayout,
"pageBreakPreview" => Self::PageBreakPreview,
_ => Self::Normal,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Pane {
pub x_split: u32,
pub y_split: u32,
pub top_left_cell: Option<CellRef>,
pub active_pane: PanePosition,
pub state: PaneState,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Selection {
pub pane: Option<PanePosition>,
pub active_cell: Option<CellRef>,
pub sqref: Vec<Range>,
}
#[expect(
clippy::struct_excessive_bools,
reason = "the independent display switches of one <sheetView> element"
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SheetView {
pub view: SheetViewType,
pub tab_selected: bool,
pub zoom_scale: Option<u32>,
pub zoom_scale_normal: Option<u32>,
pub zoom_scale_page_layout: Option<u32>,
pub zoom_scale_sheet_layout: Option<u32>,
pub top_left_cell: Option<CellRef>,
pub show_grid_lines: bool,
pub show_row_col_headers: bool,
pub show_zeros: bool,
pub right_to_left: bool,
pub workbook_view_id: u32,
pub pane: Option<Pane>,
pub selections: Vec<Selection>,
}
impl Default for SheetView {
fn default() -> Self {
Self {
view: SheetViewType::default(),
tab_selected: false,
zoom_scale: None,
zoom_scale_normal: None,
zoom_scale_page_layout: None,
zoom_scale_sheet_layout: None,
top_left_cell: None,
show_grid_lines: true,
show_row_col_headers: true,
show_zeros: true,
right_to_left: false,
workbook_view_id: 0,
pane: None,
selections: Vec::new(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ValidationType {
#[default]
None,
Custom,
Date,
Decimal,
List,
TextLength,
Time,
Whole,
}
impl ValidationType {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Custom => "custom",
Self::Date => "date",
Self::Decimal => "decimal",
Self::List => "list",
Self::TextLength => "textLength",
Self::Time => "time",
Self::Whole => "whole",
}
}
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"custom" => Self::Custom,
"date" => Self::Date,
"decimal" => Self::Decimal,
"list" => Self::List,
"textLength" => Self::TextLength,
"time" => Self::Time,
"whole" => Self::Whole,
_ => Self::None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ValidationErrorStyle {
#[default]
Stop,
Warning,
Information,
}
impl ValidationErrorStyle {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Stop => "stop",
Self::Warning => "warning",
Self::Information => "information",
}
}
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"warning" => Self::Warning,
"information" => Self::Information,
_ => Self::Stop,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ValidationOperator {
#[default]
Between,
NotBetween,
Equal,
NotEqual,
GreaterThan,
LessThan,
GreaterThanOrEqual,
LessThanOrEqual,
}
impl ValidationOperator {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Between => "between",
Self::NotBetween => "notBetween",
Self::Equal => "equal",
Self::NotEqual => "notEqual",
Self::GreaterThan => "greaterThan",
Self::LessThan => "lessThan",
Self::GreaterThanOrEqual => "greaterThanOrEqual",
Self::LessThanOrEqual => "lessThanOrEqual",
}
}
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"notBetween" => Self::NotBetween,
"equal" => Self::Equal,
"notEqual" => Self::NotEqual,
"greaterThan" => Self::GreaterThan,
"lessThan" => Self::LessThan,
"greaterThanOrEqual" => Self::GreaterThanOrEqual,
"lessThanOrEqual" => Self::LessThanOrEqual,
_ => Self::Between,
}
}
}
#[expect(
clippy::struct_excessive_bools,
reason = "the independent flags of one <dataValidation> element"
)]
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DataValidation {
pub sqref: Vec<Range>,
pub kind: ValidationType,
pub operator: ValidationOperator,
pub formula1: String,
pub formula2: String,
pub allow_blank: bool,
pub hide_drop_down: bool,
pub show_input_message: bool,
pub show_error_message: bool,
pub error_title: String,
pub error: String,
pub prompt_title: String,
pub prompt: String,
pub error_style: ValidationErrorStyle,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SheetProperties {
pub tab_color: Option<Color>,
pub summary_below: bool,
pub summary_right: bool,
pub fit_to_page: bool,
pub code_name: Option<String>,
}
impl Default for SheetProperties {
fn default() -> Self {
Self {
tab_color: None,
summary_below: true,
summary_right: true,
fit_to_page: false,
code_name: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PageMargins {
pub left: f64,
pub right: f64,
pub top: f64,
pub bottom: f64,
pub header: f64,
pub footer: f64,
}
impl Default for PageMargins {
fn default() -> Self {
Self {
left: 0.7,
right: 0.7,
top: 0.75,
bottom: 0.75,
header: 0.3,
footer: 0.3,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Orientation {
#[default]
Default,
Portrait,
Landscape,
}
impl Orientation {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Default => "default",
Self::Portrait => "portrait",
Self::Landscape => "landscape",
}
}
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"portrait" => Self::Portrait,
"landscape" => Self::Landscape,
_ => Self::Default,
}
}
}
#[expect(
clippy::struct_excessive_bools,
reason = "the independent switches of one <pageSetup> element"
)]
#[derive(Debug, Clone, PartialEq, Default)]
pub struct PageSetup {
pub paper_size: Option<u32>,
pub orientation: Orientation,
pub scale: Option<u32>,
pub fit_to_width: Option<u32>,
pub fit_to_height: Option<u32>,
pub first_page_number: Option<u32>,
pub use_first_page_number: bool,
pub printer_settings: Option<String>,
pub horizontal_dpi: Option<u32>,
pub vertical_dpi: Option<u32>,
pub over_then_down: bool,
pub black_and_white: bool,
pub draft: bool,
}
#[expect(
clippy::struct_excessive_bools,
reason = "the four independent switches of one <printOptions> element"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PrintOptions {
pub horizontal_centered: bool,
pub vertical_centered: bool,
pub headings: bool,
pub grid_lines: bool,
}
#[expect(
clippy::struct_excessive_bools,
reason = "the independent switches of one <headerFooter> element"
)]
#[derive(Debug, Clone, PartialEq)]
pub struct HeaderFooter {
pub different_odd_even: bool,
pub different_first: bool,
pub scale_with_doc: bool,
pub align_with_margins: bool,
pub odd_header: String,
pub odd_footer: String,
pub even_header: String,
pub even_footer: String,
pub first_header: String,
pub first_footer: String,
}
impl Default for HeaderFooter {
fn default() -> Self {
Self {
different_odd_even: false,
different_first: false,
scale_with_doc: true,
align_with_margins: true,
odd_header: String::new(),
odd_footer: String::new(),
even_header: String::new(),
even_footer: String::new(),
first_header: String::new(),
first_footer: String::new(),
}
}
}
impl HeaderFooter {
#[must_use]
pub fn is_meaningful(&self) -> bool {
self.different_odd_even
|| self.different_first
|| !self.scale_with_doc
|| !self.align_with_margins
|| ![
&self.odd_header,
&self.odd_footer,
&self.even_header,
&self.even_footer,
&self.first_header,
&self.first_footer,
]
.iter()
.all(|s| s.is_empty())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PageBreak {
pub at: u32,
pub max: Option<u32>,
pub manual: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LinkTarget {
Inside(String),
Outside(String),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Hyperlink {
pub range: Range,
pub target: LinkTarget,
pub display: Option<String>,
pub tooltip: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DefinedName {
pub name: String,
pub sheet: Option<usize>,
pub formula: String,
pub hidden: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CfRuleType {
#[default]
CellIs,
Expression,
ColorScale,
DataBar,
IconSet,
Top10,
UniqueValues,
DuplicateValues,
ContainsText,
NotContainsText,
BeginsWith,
EndsWith,
ContainsBlanks,
NotContainsBlanks,
ContainsErrors,
NotContainsErrors,
TimePeriod,
AboveAverage,
}
impl CfRuleType {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::CellIs => "cellIs",
Self::Expression => "expression",
Self::ColorScale => "colorScale",
Self::DataBar => "dataBar",
Self::IconSet => "iconSet",
Self::Top10 => "top10",
Self::UniqueValues => "uniqueValues",
Self::DuplicateValues => "duplicateValues",
Self::ContainsText => "containsText",
Self::NotContainsText => "notContainsText",
Self::BeginsWith => "beginsWith",
Self::EndsWith => "endsWith",
Self::ContainsBlanks => "containsBlanks",
Self::NotContainsBlanks => "notContainsBlanks",
Self::ContainsErrors => "containsErrors",
Self::NotContainsErrors => "notContainsErrors",
Self::TimePeriod => "timePeriod",
Self::AboveAverage => "aboveAverage",
}
}
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"expression" => Self::Expression,
"colorScale" => Self::ColorScale,
"dataBar" => Self::DataBar,
"iconSet" => Self::IconSet,
"top10" => Self::Top10,
"uniqueValues" => Self::UniqueValues,
"duplicateValues" => Self::DuplicateValues,
"containsText" => Self::ContainsText,
"notContainsText" => Self::NotContainsText,
"beginsWith" => Self::BeginsWith,
"endsWith" => Self::EndsWith,
"containsBlanks" => Self::ContainsBlanks,
"notContainsBlanks" => Self::NotContainsBlanks,
"containsErrors" => Self::ContainsErrors,
"notContainsErrors" => Self::NotContainsErrors,
"timePeriod" => Self::TimePeriod,
"aboveAverage" => Self::AboveAverage,
_ => Self::CellIs,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CfOperator {
#[default]
Between,
NotBetween,
Equal,
NotEqual,
GreaterThan,
LessThan,
GreaterThanOrEqual,
LessThanOrEqual,
ContainsText,
NotContains,
BeginsWith,
EndsWith,
}
impl CfOperator {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Between => "between",
Self::NotBetween => "notBetween",
Self::Equal => "equal",
Self::NotEqual => "notEqual",
Self::GreaterThan => "greaterThan",
Self::LessThan => "lessThan",
Self::GreaterThanOrEqual => "greaterThanOrEqual",
Self::LessThanOrEqual => "lessThanOrEqual",
Self::ContainsText => "containsText",
Self::NotContains => "notContains",
Self::BeginsWith => "beginsWith",
Self::EndsWith => "endsWith",
}
}
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"notBetween" => Self::NotBetween,
"equal" => Self::Equal,
"notEqual" => Self::NotEqual,
"greaterThan" => Self::GreaterThan,
"lessThan" => Self::LessThan,
"greaterThanOrEqual" => Self::GreaterThanOrEqual,
"lessThanOrEqual" => Self::LessThanOrEqual,
"containsText" => Self::ContainsText,
"notContains" => Self::NotContains,
"beginsWith" => Self::BeginsWith,
"endsWith" => Self::EndsWith,
_ => Self::Between,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CfValueType {
#[default]
Number,
Percent,
Percentile,
Min,
Max,
Formula,
}
impl CfValueType {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Number => "num",
Self::Percent => "percent",
Self::Percentile => "percentile",
Self::Min => "min",
Self::Max => "max",
Self::Formula => "formula",
}
}
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"percent" => Self::Percent,
"percentile" => Self::Percentile,
"min" => Self::Min,
"max" => Self::Max,
"formula" => Self::Formula,
_ => Self::Number,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CfValue {
pub kind: CfValueType,
pub value: String,
pub greater_or_equal: bool,
}
impl Default for CfValue {
fn default() -> Self {
Self {
kind: CfValueType::default(),
value: String::new(),
greater_or_equal: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CfScale {
Color {
values: Vec<CfValue>,
colors: Vec<Color>,
},
DataBar {
values: Vec<CfValue>,
color: Color,
min_length: Option<u32>,
max_length: Option<u32>,
show_value: bool,
},
IconSet {
values: Vec<CfValue>,
set: Option<String>,
show_value: bool,
percent: bool,
reverse: bool,
},
}
#[expect(
clippy::struct_excessive_bools,
reason = "the independent flags of one <cfRule> element"
)]
#[derive(Debug, Clone, PartialEq, Default)]
pub struct CfRule {
pub kind: CfRuleType,
pub priority: i32,
pub dxf: Option<u32>,
pub stop_if_true: bool,
pub operator: Option<CfOperator>,
pub text: Option<String>,
pub time_period: Option<String>,
pub rank: Option<u32>,
pub percent: bool,
pub bottom: bool,
pub above_average: bool,
pub equal_average: bool,
pub std_dev: Option<i32>,
pub formulas: Vec<String>,
pub scale: Option<CfScale>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ConditionalFormat {
pub sqref: Vec<Range>,
pub rules: Vec<CfRule>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpaquePart {
pub path: String,
pub content_type: Option<String>,
pub data: Vec<u8>,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ExternalBook {
pub path: Option<String>,
pub sheets: Vec<ExternalSheet>,
}
impl ExternalBook {
#[must_use]
pub fn sheet(&self, name: &str) -> Option<&ExternalSheet> {
self.sheets
.iter()
.find(|s| s.name.eq_ignore_ascii_case(name))
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ExternalSheet {
pub name: String,
pub cells: BTreeMap<(Row, Col), CellValue>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attachment {
pub kind: String,
pub target: String,
}
impl Attachment {
#[must_use]
pub fn role(&self) -> &str {
self.kind.rsplit('/').next().unwrap_or(&self.kind)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SheetVisibility {
#[default]
Visible,
Hidden,
VeryHidden,
}
impl SheetVisibility {
#[must_use]
pub fn as_str(self) -> Option<&'static str> {
match self {
Self::Visible => None,
Self::Hidden => Some("hidden"),
Self::VeryHidden => Some("veryHidden"),
}
}
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"hidden" => Self::Hidden,
"veryHidden" => Self::VeryHidden,
_ => Self::Visible,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Worksheet {
title: String,
pub visibility: SheetVisibility,
cells: Arc<BTreeMap<Row, Vec<(Col, Cell)>>>,
count: usize,
pub merges: Vec<Range>,
pub array_formulas: Vec<Range>,
pub columns: Vec<ColumnRun>,
pub rows: BTreeMap<Row, RowProperties>,
pub default_column_width: Option<f64>,
pub default_row_height: Option<f64>,
pub view: SheetView,
pub data_validations: Vec<DataValidation>,
pub properties: SheetProperties,
pub margins: PageMargins,
pub page_setup: PageSetup,
pub print_options: PrintOptions,
pub header_footer: HeaderFooter,
pub row_breaks: Vec<PageBreak>,
pub col_breaks: Vec<PageBreak>,
pub hyperlinks: Vec<Hyperlink>,
pub conditional_formats: Vec<ConditionalFormat>,
pub protection: SheetProtection,
pub protected_ranges: Vec<ProtectedRange>,
pub auto_filter: Option<AutoFilter>,
pub comments: BTreeMap<CellRef, Comment>,
pub pivot_tables: Vec<pivot::PivotTable>,
pub tables: Vec<table::Table>,
pub charts: Vec<chart::Chart>,
pub extended_charts: Vec<chart::ChartEx>,
pub images: Vec<image::Image>,
pub shapes: Vec<shape::Shape>,
pub extensions: Option<String>,
pub attachments: Vec<Attachment>,
}
impl Worksheet {
pub fn new(title: impl Into<String>) -> Result<Self> {
Ok(Self {
title: validate_sheet_title(title.into())?,
..Self::default()
})
}
#[must_use]
pub fn title(&self) -> &str {
&self.title
}
pub fn set_title(&mut self, title: impl Into<String>) -> Result<()> {
self.title = validate_sheet_title(title.into())?;
Ok(())
}
#[must_use]
pub fn get(&self, at: CellRef) -> Option<&Cell> {
let line = self.cells.get(&at.row)?;
line.binary_search_by_key(&at.col, |(col, _)| *col)
.ok()
.map(|i| &line[i].1)
}
pub fn set(&mut self, at: CellRef, value: impl Into<CellValue>) {
self.entry(at).value = value.into();
}
pub fn set_styled(&mut self, at: CellRef, value: impl Into<CellValue>, style: StyleId) {
let cell = self.entry(at);
cell.value = value.into();
cell.style = style;
}
pub fn set_row<V: Into<CellValue>>(
&mut self,
from: CellRef,
values: impl IntoIterator<Item = V>,
) {
for (offset, value) in values.into_iter().enumerate() {
let Ok(offset) = u32::try_from(offset) else {
return;
};
let Some(col) = from.col.index().checked_add(offset).and_then(Col::new) else {
return;
};
self.set(CellRef::new(col, from.row), value);
}
}
pub fn entry(&mut self, at: CellRef) -> &mut Cell {
let cells = Arc::make_mut(&mut self.cells);
if !cells.contains_key(&at.row) {
let width = cells.last_key_value().map_or(0, |(_, line)| line.len());
cells.insert(at.row, Vec::with_capacity(width));
}
let line = cells.entry(at.row).or_default();
let index = match line.last() {
Some((col, _)) if *col < at.col => Err(line.len()),
_ => line.binary_search_by_key(&at.col, |(col, _)| *col),
};
let index = match index {
Ok(i) => i,
Err(i) => {
line.insert(i, (at.col, Cell::default()));
self.count += 1;
i
}
};
&mut line[index].1
}
pub fn remove(&mut self, at: CellRef) -> Option<Cell> {
let line = self.cells.get(&at.row)?;
let index = line.binary_search_by_key(&at.col, |(col, _)| *col).ok()?;
let cells = Arc::make_mut(&mut self.cells);
let line = cells.get_mut(&at.row)?;
let (_, cell) = line.remove(index);
if line.is_empty() {
cells.remove(&at.row);
}
self.count -= 1;
Some(cell)
}
#[must_use]
pub const fn len(&self) -> usize {
self.count
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.count == 0
}
pub fn iter(&self) -> impl Iterator<Item = (CellRef, &Cell)> {
self.cells.iter().flat_map(|(&row, line)| {
line.iter()
.map(move |(col, cell)| (CellRef::new(*col, row), cell))
})
}
pub fn row_cells(&self, row: Row) -> impl Iterator<Item = (Col, &Cell)> {
self.cells
.get(&row)
.into_iter()
.flat_map(|line| line.iter().map(|(col, cell)| (*col, cell)))
}
pub fn shrink_to_fit(&mut self) {
for line in Arc::make_mut(&mut self.cells).values_mut() {
line.shrink_to_fit();
}
}
#[must_use]
pub fn column_run(&self, col: Col) -> Option<&ColumnRun> {
self.columns
.iter()
.rev()
.find(|run| run.first <= col && col <= run.last)
}
#[must_use]
pub fn column_width(&self, col: Col) -> Option<f64> {
self.column_run(col)
.and_then(|run| run.width)
.or(self.default_column_width)
}
#[must_use]
pub fn column_outline_level(&self, col: Col) -> u8 {
self.column_run(col).map_or(0, |run| run.outline_level)
}
#[must_use]
pub fn row_outline_level(&self, row: Row) -> u8 {
self.rows.get(&row).map_or(0, |r| r.outline_level)
}
#[must_use]
pub fn row_height(&self, row: Row) -> Option<f64> {
self.rows
.get(&row)
.and_then(|r| r.height)
.or(self.default_row_height)
}
#[must_use]
pub fn dimension(&self) -> Option<Range> {
let (&first_row, _) = self.cells.first_key_value()?;
let (&last_row, _) = self.cells.last_key_value()?;
let mut columns = self
.cells
.values()
.filter_map(|line| Some((line.first()?.0, line.last()?.0)));
let (mut min_col, mut max_col) = columns.next()?;
for (first, last) in columns {
min_col = min_col.min(first);
max_col = max_col.max(last);
}
Some(Range::new(
CellRef::new(min_col, first_row),
CellRef::new(max_col, last_row),
))
}
}
#[derive(Debug, Clone)]
pub struct Spreadsheet {
sheets: Vec<Worksheet>,
active: usize,
pub styles: StyleTable,
pub epoch: Epoch,
pub defined_names: Vec<DefinedName>,
pub workbook_properties: Vec<(String, String)>,
pub calculation_properties: Vec<(String, String)>,
pub protection: WorkbookProtection,
pub attachments: Vec<Attachment>,
pub doc_props: Vec<Attachment>,
pub parts: Vec<OpaquePart>,
pub external: Vec<ExternalBook>,
pub theme: Option<String>,
pub pivot_caches: Vec<pivot::PivotCache>,
pub workbook_extensions: Option<String>,
pub style_extensions: Option<String>,
pub table_styles: Option<String>,
pub palette: Option<String>,
}
impl Default for Spreadsheet {
fn default() -> Self {
Self {
sheets: vec![Worksheet::new("Worksheet").unwrap_or_default()],
active: 0,
styles: StyleTable::default(),
epoch: Epoch::default(),
defined_names: Vec::new(),
workbook_properties: Vec::new(),
calculation_properties: Vec::new(),
protection: WorkbookProtection::default(),
attachments: Vec::new(),
doc_props: Vec::new(),
parts: Vec::new(),
external: Vec::new(),
theme: None,
pivot_caches: Vec::new(),
workbook_extensions: None,
style_extensions: None,
table_styles: None,
palette: None,
}
}
}
impl Spreadsheet {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn empty() -> Self {
Self {
sheets: Vec::new(),
active: 0,
..Self::default()
}
}
#[must_use]
pub fn sheets(&self) -> &[Worksheet] {
&self.sheets
}
#[must_use]
pub fn sheet(&self, index: usize) -> Option<&Worksheet> {
self.sheets.get(index)
}
pub fn sheet_mut(&mut self, index: usize) -> Option<&mut Worksheet> {
self.sheets.get_mut(index)
}
#[must_use]
pub fn sheet_by_name(&self, name: &str) -> Option<&Worksheet> {
self.sheets.get(self.sheet_index_by_name(name)?)
}
#[must_use]
pub fn sheet_index_by_name(&self, name: &str) -> Option<usize> {
let name = name.to_lowercase();
self.sheets
.iter()
.position(|s| s.title.to_lowercase() == name)
}
#[must_use]
pub fn formatted(&self, sheet: usize, at: CellRef) -> String {
let Some(cell) = self.sheets.get(sheet).and_then(|s| s.get(at)) else {
return String::new();
};
let code = self
.styles
.get(cell.style)
.map_or(crate::style::format::GENERAL, |s| s.number_format.code());
cell.value.display(code, self.epoch)
}
#[must_use]
pub fn formatted_at(&self, sheet: usize, row: u32, column: u32) -> String {
let (Ok(row), Ok(column)) = (
Row::from_one_based(u64::from(row)),
Col::from_one_based(u64::from(column)),
) else {
return String::new();
};
self.formatted(sheet, CellRef::new(column, row))
}
#[must_use]
pub const fn active_index(&self) -> usize {
self.active
}
#[must_use]
pub fn active_sheet(&self) -> Option<&Worksheet> {
self.sheets.get(self.active)
}
pub fn active_sheet_mut(&mut self) -> Option<&mut Worksheet> {
self.sheets.get_mut(self.active)
}
pub(crate) fn take_sheet(&mut self, index: usize) -> Option<Worksheet> {
if index >= self.sheets.len() {
return None;
}
let gone = self.sheets.remove(index);
self.active = self.active.min(self.sheets.len().saturating_sub(1));
Some(gone)
}
pub fn set_active(&mut self, index: usize) -> Result<()> {
if index >= self.sheets.len() {
return Err(Error::InvalidSheetName(index.to_string()));
}
self.active = index;
Ok(())
}
pub fn add_sheet(&mut self, sheet: Worksheet) -> Result<usize> {
if self.sheet_by_name(sheet.title()).is_some() {
return Err(Error::DuplicateSheetName(sheet.title));
}
self.sheets.push(sheet);
Ok(self.sheets.len() - 1)
}
}
fn validate_sheet_title(title: String) -> Result<String> {
let len = title.chars().count();
if len == 0
|| len > SHEET_TITLE_MAX_LENGTH
|| title.contains(SHEET_TITLE_INVALID_CHARS)
|| title.starts_with('\'')
|| title.ends_with('\'')
{
return Err(Error::InvalidSheetName(title));
}
Ok(title)
}
#[cfg(test)]
mod tests {
#[test]
fn cells_keep_row_and_column_order_however_they_arrive() {
let mut sheet = Worksheet::new("S").unwrap();
let at = |a: &str| CellRef::parse(a).unwrap();
for a in ["C2", "A2", "B5", "B2", "A1"] {
sheet.set(at(a), a);
}
sheet.set(at("B2"), "again");
let order: Vec<String> = sheet.iter().map(|(a, _)| a.to_string()).collect();
assert_eq!(order, ["A1", "A2", "B2", "C2", "B5"]);
assert_eq!(sheet.len(), 5);
assert_eq!(sheet.dimension(), Some(Range::parse("A1:C5").unwrap()));
assert!(sheet.remove(at("B5")).is_some());
assert!(sheet.remove(at("B5")).is_none());
assert_eq!(sheet.len(), 4);
assert_eq!(sheet.dimension(), Some(Range::parse("A1:C2").unwrap()));
let row: Vec<crate::Col> = sheet
.row_cells(Row::new(1).unwrap())
.map(|(c, _)| c)
.collect();
assert_eq!(row.len(), 3);
}
use super::{CellValue, MAX_STRING_LENGTH, Spreadsheet, Worksheet};
use crate::coordinate::{CellRef, Range, Row};
use crate::style::StyleId;
fn r(a: &str) -> CellRef {
CellRef::parse(a).expect("test reference is valid")
}
#[test]
fn sheet_titles_follow_excel_rules() {
assert!(Worksheet::new("Data").is_ok());
assert!(Worksheet::new("Данные").is_ok(), "non-ASCII names are fine");
assert!(Worksheet::new("").is_err(), "empty name");
assert!(Worksheet::new("a".repeat(31)).is_ok());
assert!(
Worksheet::new("a".repeat(32)).is_err(),
"the limit is 31 characters"
);
for bad in ["a*b", "a:b", "a/b", "a\\b", "a?b", "a[b", "a]b"] {
assert!(Worksheet::new(bad).is_err(), "banned character in {bad:?}");
}
assert!(
Worksheet::new("'quoted'").is_err(),
"apostrophe at the edges"
);
}
#[test]
fn cells_store_and_iterate_in_write_order() {
let mut ws = Worksheet::new("S").unwrap();
ws.set(r("C1"), 3.0);
ws.set(r("A2"), "text");
ws.set(r("A1"), true);
let order: Vec<String> = ws.iter().map(|(at, _)| at.to_string()).collect();
assert_eq!(order, ["A1", "C1", "A2"]);
assert_eq!(ws.len(), 3);
assert_eq!(ws.get(r("A1")).unwrap().value, CellValue::Bool(true));
assert!(ws.get(r("B1")).is_none());
}
#[test]
fn set_preserves_style() {
let mut ws = Worksheet::new("S").unwrap();
let styled = StyleId::from_index(7);
ws.entry(r("A1")).style = styled;
ws.set(r("A1"), 42.0);
assert_eq!(
ws.get(r("A1")).unwrap().style,
styled,
"rewriting a value keeps the style"
);
}
#[test]
fn a_row_yields_only_its_own_cells() {
let mut ws = Worksheet::new("S").unwrap();
for a in ["A1", "C1", "B2", "Z2", "A3"] {
ws.set(r(a), 1.0);
}
let row2 = Row::from_one_based(2).unwrap();
let cols: Vec<u32> = ws.row_cells(row2).map(|(col, _)| col.one_based()).collect();
assert_eq!(cols, vec![2, 26]);
}
#[test]
fn dimension_covers_used_cells() {
let mut ws = Worksheet::new("S").unwrap();
assert!(ws.dimension().is_none(), "an empty sheet has no dimension");
ws.set(r("C5"), 1.0);
ws.set(r("B2"), 1.0);
ws.set(r("D3"), 1.0);
assert_eq!(ws.dimension().unwrap(), Range::parse("B2:D5").unwrap());
}
#[test]
fn text_is_kept_as_written_and_truncated() {
assert_eq!(
CellValue::text("a\r\nb\rc"),
CellValue::Text("a\r\nb\rc".into()),
"a line break the author typed is theirs, CR and all"
);
let long = "я".repeat(MAX_STRING_LENGTH + 10);
let CellValue::Text(t) = CellValue::text(long) else {
panic!("expected text");
};
assert_eq!(
t.chars().count(),
MAX_STRING_LENGTH,
"truncated by characters, not bytes"
);
}
#[test]
fn workbook_manages_sheets() {
let mut wb = Spreadsheet::new();
assert_eq!(wb.sheets().len(), 1);
assert_eq!(wb.active_sheet().unwrap().title(), "Worksheet");
let idx = wb.add_sheet(Worksheet::new("Второй").unwrap()).unwrap();
assert_eq!(idx, 1);
assert!(
wb.sheet_by_name("ВТОРОЙ").is_some(),
"sheet lookup is case-insensitive beyond ASCII"
);
assert!(
wb.add_sheet(Worksheet::new("второй").unwrap()).is_err(),
"duplicate name"
);
wb.set_active(1).unwrap();
assert_eq!(wb.active_sheet().unwrap().title(), "Второй");
assert!(wb.set_active(9).is_err());
}
#[test]
fn a_value_is_read_through_its_formula() {
let computed = CellValue::Formula {
formula: "1+2".to_owned(),
cached: Some(Box::new(CellValue::Number(3.0))),
};
assert_eq!(computed.as_number(), Some(3.0));
assert_eq!(computed.result(), &CellValue::Number(3.0));
let fresh = CellValue::formula("1+2");
assert_eq!(fresh.result(), &CellValue::Empty);
assert_eq!(fresh.as_number(), None);
assert_eq!(CellValue::text("Ёж").as_str(), Some("Ёж"));
assert_eq!(CellValue::Bool(true).as_bool(), Some(true));
let div0 = crate::CellError::Div0;
assert_eq!(CellValue::Error(div0).as_error(), Some(div0));
assert_eq!(CellValue::Bool(true).as_number(), None);
}
#[test]
fn a_cell_shows_its_value_through_its_own_format() {
use crate::style::{NumberFormat, Style};
let mut book = Spreadsheet::empty();
let mut sheet = Worksheet::new("Sheet1").unwrap();
let at = CellRef::parse("A1").unwrap();
sheet.set(at, 45292.0);
let dated = book.styles.intern(Style {
number_format: NumberFormat::Custom("DD.MM.YYYY".to_owned()),
..Style::default()
});
sheet.entry(at).style = dated;
let plain = CellRef::parse("A2").unwrap();
sheet.set(plain, 45292.0);
book.add_sheet(sheet).unwrap();
assert_eq!(book.formatted(0, at), "01.01.2024");
assert_eq!(book.formatted(0, plain), "45292");
assert_eq!(book.formatted(0, CellRef::parse("Z99").unwrap()), "");
assert_eq!(book.formatted(7, at), "");
}
#[test]
fn a_row_of_values_stops_at_the_last_column() {
let mut sheet = Worksheet::new("Sheet1").unwrap();
let last = CellRef::new(
crate::Col::new(crate::coordinate::MAX_COL - 1).unwrap(),
crate::Row::new(0).unwrap(),
);
sheet.set_row(last, [1.0, 2.0, 3.0]);
assert_eq!(sheet.get(last).and_then(|c| c.value.as_number()), Some(1.0));
assert_eq!(sheet.len(), 1, "the other two had nowhere to go");
let a1 = CellRef::parse("A1").unwrap();
sheet.set_row(a1, ["a", "b", "c"]);
assert_eq!(
sheet
.get(CellRef::parse("C1").unwrap())
.unwrap()
.value
.as_str(),
Some("c")
);
}
#[test]
fn a_value_and_its_style_are_written_together() {
use crate::style::Style;
let mut book = Spreadsheet::empty();
let mut sheet = Worksheet::new("Sheet1").unwrap();
let mut bold = Style::default();
bold.font.bold = true;
let bold = book.styles.intern(bold);
let at = CellRef::parse("A1").unwrap();
sheet.set_styled(at, "Итого", bold);
assert_eq!(sheet.get(at).unwrap().style, bold);
assert_eq!(sheet.get(at).unwrap().value.as_str(), Some("Итого"));
book.add_sheet(sheet).unwrap();
assert_eq!(book.formatted_at(0, 1, 1), "Итого");
assert_eq!(book.formatted_at(0, 0, 1), "", "row zero is not a row");
}
}