use std::collections::BTreeMap;
use std::fmt;
use crate::exceptions::{Error, Result};
use crate::worksheet::cell_range::CellRange;
use crate::worksheet::Worksheet;
pub const TOTALS_ROW_FUNCTIONS: [&str; 9] = [
"sum",
"min",
"max",
"average",
"count",
"countNums",
"stdDev",
"var",
"custom",
];
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TableStyleInfo {
pub name: Option<String>,
pub show_first_column: Option<bool>,
pub show_last_column: Option<bool>,
pub show_row_stripes: Option<bool>,
pub show_column_stripes: Option<bool>,
}
impl TableStyleInfo {
pub fn new() -> Self {
TableStyleInfo::default()
}
pub fn banded() -> Self {
TableStyleInfo {
name: Some("TableStyleMedium9".to_string()),
show_row_stripes: Some(true),
..TableStyleInfo::default()
}
}
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn with_row_stripes(mut self, stripes: bool) -> Self {
self.show_row_stripes = Some(stripes);
self
}
pub fn with_column_stripes(mut self, stripes: bool) -> Self {
self.show_column_stripes = Some(stripes);
self
}
pub fn with_outer_columns(mut self, emphasis: bool) -> Self {
self.show_first_column = Some(emphasis);
self.show_last_column = Some(emphasis);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TableFormula {
pub array: Option<bool>,
pub text: String,
}
impl TableFormula {
pub fn new(text: &str) -> Self {
TableFormula {
array: None,
text: text.strip_prefix('=').unwrap_or(text).to_string(),
}
}
pub fn as_array(mut self) -> Self {
self.array = Some(true);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TableColumn {
pub id: u32,
pub name: String,
pub totals_row_function: Option<String>,
pub totals_row_label: Option<String>,
pub header_row_dxf_id: Option<u32>,
pub data_dxf_id: Option<u32>,
pub totals_row_dxf_id: Option<u32>,
pub header_row_cell_style: Option<String>,
pub data_cell_style: Option<String>,
pub totals_row_cell_style: Option<String>,
pub calculated_column_formula: Option<TableFormula>,
pub totals_row_formula: Option<TableFormula>,
}
impl TableColumn {
pub fn new(id: u32, name: impl Into<String>) -> Self {
TableColumn {
id,
name: name.into(),
..TableColumn::default()
}
}
pub fn with_totals_function(mut self, function: &str) -> Result<Self> {
if !TOTALS_ROW_FUNCTIONS.contains(&function) {
return Err(Error::Value(format!(
"{function} is not a totals row function; expected one of {}",
TOTALS_ROW_FUNCTIONS.join(", ")
)));
}
self.totals_row_function = Some(function.to_string());
Ok(self)
}
pub fn with_calculated_formula(mut self, formula: &str) -> Self {
self.calculated_column_formula = Some(TableFormula::new(formula));
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Table {
pub id: u32,
pub display_name: String,
pub name: Option<String>,
pub reference: String,
pub comment: Option<String>,
pub table_type: Option<String>,
pub header_row_count: Option<u32>,
pub insert_row: Option<bool>,
pub totals_row_count: Option<u32>,
pub totals_row_shown: Option<bool>,
pub header_row_dxf_id: Option<u32>,
pub data_dxf_id: Option<u32>,
pub totals_row_dxf_id: Option<u32>,
pub header_row_cell_style: Option<String>,
pub data_cell_style: Option<String>,
pub totals_row_cell_style: Option<String>,
pub columns: Vec<TableColumn>,
pub style_info: TableStyleInfo,
}
impl Table {
pub fn new(display_name: &str, reference: &str) -> Result<Self> {
if display_name.contains(' ') {
return Err(Error::Value(
"a table name cannot contain a space".to_string(),
));
}
if display_name.is_empty() {
return Err(Error::Value("a table needs a name".to_string()));
}
CellRange::parse(reference)?;
Ok(Table {
id: 1,
display_name: display_name.to_string(),
name: None,
reference: reference.to_string(),
comment: None,
table_type: None,
header_row_count: Some(1),
insert_row: None,
totals_row_count: None,
totals_row_shown: None,
header_row_dxf_id: None,
data_dxf_id: None,
totals_row_dxf_id: None,
header_row_cell_style: None,
data_cell_style: None,
totals_row_cell_style: None,
columns: Vec::new(),
style_info: TableStyleInfo::default(),
})
}
pub fn formula_name(&self) -> &str {
self.name.as_deref().unwrap_or(&self.display_name)
}
pub fn with_id(mut self, id: u32) -> Self {
self.id = id;
self
}
pub fn with_comment(mut self, comment: impl Into<String>) -> Self {
self.comment = Some(comment.into());
self
}
pub fn with_style(mut self, style: TableStyleInfo) -> Self {
self.style_info = style;
self
}
pub fn with_column(mut self, column: TableColumn) -> Self {
self.columns.push(column);
self
}
pub fn with_columns(mut self, columns: impl IntoIterator<Item = TableColumn>) -> Self {
self.columns.extend(columns);
self
}
pub fn set_header_row(&mut self, present: bool) -> &mut Self {
self.header_row_count = if present { Some(1) } else { Some(0) };
self
}
pub fn set_totals_row(&mut self, shown: bool) -> &mut Self {
self.totals_row_shown = Some(shown);
self.totals_row_count = Some(if shown { 1 } else { 0 });
self
}
pub fn column_names(&self) -> Vec<&str> {
self.columns.iter().map(|c| c.name.as_str()).collect()
}
pub fn initialise_columns(&mut self, sheet: &Worksheet) -> Result<()> {
let bounds = CellRange::parse(&self.reference)?;
let has_header = self.header_row_count.unwrap_or(1) != 0;
let header_row = if has_header {
bounds.min_row
} else {
bounds.min_row
};
let mut columns = Vec::new();
for index in 0..(bounds.max_col - bounds.min_col + 1) {
let column = bounds.min_col + index;
let name = if has_header {
let coordinate = format!(
"{}{header_row}",
crate::cell::utils::get_column_letter(column)?
);
match sheet.cell_value(&coordinate) {
Some(crate::cell::cell::CellValue::Text(text)) if !text.is_empty() => text,
Some(crate::cell::cell::CellValue::Number(number)) => {
crate::xml::functions::safe_string(number)
}
Some(crate::cell::cell::CellValue::DateTime(date)) => {
date.format("%Y-%m-%d").to_string()
}
_ => format!("Column{column}"),
}
} else {
format!("Column{column}")
};
columns.push(TableColumn::new(column, name));
}
self.columns = columns;
Ok(())
}
}
impl fmt::Display for Table {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.formula_name(), self.reference)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TableList {
tables: BTreeMap<String, Table>,
}
impl TableList {
pub fn new() -> Self {
TableList::default()
}
pub fn add(&mut self, table: Table) -> Result<()> {
self.tables.insert(table.formula_name().to_string(), table);
Ok(())
}
pub fn get(&self, name: &str) -> Option<&Table> {
self.tables.get(name)
}
pub fn get_mut(&mut self, name: &str) -> Option<&mut Table> {
self.tables.get_mut(name)
}
pub fn get_by_range(&self, reference: &str) -> Option<&Table> {
self.tables.values().find(|t| t.reference == reference)
}
pub fn remove(&mut self, name: &str) -> Option<Table> {
self.tables.remove(name)
}
pub fn len(&self) -> usize {
self.tables.len()
}
pub fn is_empty(&self) -> bool {
self.tables.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = &Table> {
self.tables.values()
}
pub fn names(&self) -> Vec<&str> {
self.tables.keys().map(String::as_str).collect()
}
}
impl fmt::Display for TableList {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let rendered: Vec<String> = self.tables.values().map(|t| t.to_string()).collect();
f.write_str(&rendered.join(", "))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cell::cell::CellValue;
fn sheet_with_headers() -> Worksheet {
let mut ws = Worksheet::new("S").expect("title");
ws.set("A1", CellValue::text("Product")).expect("A1");
ws.set("B1", CellValue::text("Region")).expect("B1");
ws.set("C1", CellValue::text("Sales")).expect("C1");
ws
}
#[test]
fn a_table_needs_a_name_and_a_range() {
assert!(Table::new("Sales", "A1:C10").is_ok());
assert!(
Table::new("Sales Data", "A1:C10").is_err(),
"a space is refused"
);
assert!(Table::new("", "A1:C10").is_err());
assert!(Table::new("Sales", "nonsense").is_err());
}
#[test]
fn the_formula_name_defaults_to_the_display_name() {
let table = Table::new("Sales", "A1:C10").expect("a table");
assert_eq!(table.formula_name(), "Sales");
let mut renamed = table.clone();
renamed.name = Some("Q3".to_string());
assert_eq!(renamed.formula_name(), "Q3");
}
#[test]
fn columns_are_read_from_the_header_row() {
let sheet = sheet_with_headers();
let mut table = Table::new("Sales", "A1:C3").expect("a table");
table.initialise_columns(&sheet).expect("columns");
assert_eq!(table.column_names(), ["Product", "Region", "Sales"]);
assert_eq!(table.columns[0].id, 1);
assert_eq!(table.columns[2].id, 3);
}
#[test]
fn a_numeric_header_is_named_by_its_display_form() {
let mut ws = Worksheet::new("S").expect("title");
ws.set("A1", CellValue::number(2026.0)).expect("A1");
ws.set("B1", CellValue::text("Total")).expect("B1");
let mut table = Table::new("T", "A1:B3").expect("a table");
table.initialise_columns(&ws).expect("columns");
assert_eq!(table.column_names(), ["2026", "Total"]);
}
#[test]
fn a_blank_header_keeps_a_placeholder() {
let mut ws = Worksheet::new("S").expect("title");
ws.set("B1", CellValue::text("Total")).expect("B1");
let mut table = Table::new("T", "A1:B3").expect("a table");
table.initialise_columns(&ws).expect("columns");
assert_eq!(table.column_names(), ["Column1", "Total"]);
}
#[test]
fn a_table_without_a_header_row_keeps_placeholders() {
let sheet = sheet_with_headers();
let mut table = Table::new("T", "A1:C3").expect("a table");
table.set_header_row(false);
table.initialise_columns(&sheet).expect("columns");
assert_eq!(table.column_names(), ["Column1", "Column2", "Column3"]);
assert_eq!(table.header_row_count, Some(0));
}
#[test]
fn a_totals_function_is_checked_against_what_excel_accepts() {
let column = TableColumn::new(1, "Sales");
assert!(column.clone().with_totals_function("sum").is_ok());
assert!(column.clone().with_totals_function("average").is_ok());
let err = column
.with_totals_function("median")
.expect_err("not a totals function")
.to_string();
assert!(err.contains("countNums"), "{err}");
}
#[test]
fn a_table_list_keys_by_name_and_replaces_on_a_collision() {
let mut list = TableList::new();
list.add(Table::new("Sales", "A1:C3").expect("a table"))
.expect("added");
list.add(Table::new("Costs", "E1:G3").expect("a table"))
.expect("added");
assert_eq!(list.len(), 2);
assert_eq!(list.names(), ["Costs", "Sales"]);
list.add(Table::new("Sales", "A10:C12").expect("a table"))
.expect("replaced");
assert_eq!(list.len(), 2);
assert_eq!(list.get("Sales").expect("Sales").reference, "A10:C12");
assert_eq!(
list.get_by_range("E1:G3").expect("by range").display_name,
"Costs"
);
assert_eq!(list.remove("Sales").expect("removed").reference, "A10:C12");
assert!(list.get("Sales").is_none());
}
#[test]
fn a_table_renders_as_its_name_and_range() {
let table = Table::new("Sales", "A1:C3").expect("a table");
assert_eq!(table.to_string(), "Sales A1:C3");
let mut list = TableList::new();
list.add(table).expect("added");
assert_eq!(list.to_string(), "Sales A1:C3");
}
#[test]
fn a_calculated_column_formula_loses_its_equals_sign() {
let column = TableColumn::new(1, "Total").with_calculated_formula("=[@Qty]*[@Price]");
let formula = column.calculated_column_formula.expect("a formula");
assert_eq!(formula.text, "[@Qty]*[@Price]");
}
#[test]
fn banding_defaults_match_excel() {
let style = TableStyleInfo::banded();
assert_eq!(style.name.as_deref(), Some("TableStyleMedium9"));
assert_eq!(style.show_row_stripes, Some(true));
assert_eq!(style.show_column_stripes, None);
}
}