use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::coordinate::{CellRange, Coordinate, column_index_from_string, string_from_column_index};
use crate::error::ExcelError;
use crate::style::Style;
use crate::value::Value;
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Properties {
pub creator: Option<String>,
pub last_modified_by: Option<String>,
pub title: Option<String>,
pub description: Option<String>,
pub subject: Option<String>,
pub keywords: Option<String>,
pub category: Option<String>,
pub manager: Option<String>,
pub company: Option<String>,
}
impl Properties {
pub fn apply(&mut self, other: &Properties) {
let pairs: [(&mut Option<String>, &Option<String>); 9] = [
(&mut self.creator, &other.creator),
(&mut self.last_modified_by, &other.last_modified_by),
(&mut self.title, &other.title),
(&mut self.description, &other.description),
(&mut self.subject, &other.subject),
(&mut self.keywords, &other.keywords),
(&mut self.category, &other.category),
(&mut self.manager, &other.manager),
(&mut self.company, &other.company),
];
for (target, source) in pairs {
if let Some(value) = source.as_ref().filter(|value| !value.is_empty()) {
*target = Some(value.clone());
}
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Spreadsheet {
sheets: Vec<Worksheet>,
pub properties: Properties,
pub default_style: Style,
}
impl Spreadsheet {
pub fn new() -> Self {
Self::default()
}
pub fn create_sheet(&mut self, index: Option<usize>) -> usize {
let mut title = "Worksheet".to_owned();
let mut counter = 1;
while self.sheets.iter().any(|sheet| sheet.title.eq_ignore_ascii_case(&title)) {
title = format!("Worksheet {counter}");
counter += 1;
}
let sheet = Worksheet::new(title);
match index {
Some(index) if index < self.sheets.len() => {
self.sheets.insert(index, sheet);
index
}
_ => {
self.sheets.push(sheet);
self.sheets.len() - 1
}
}
}
pub fn sheets(&self) -> &[Worksheet] {
&self.sheets
}
pub fn sheets_mut(&mut self) -> &mut [Worksheet] {
&mut self.sheets
}
pub fn sheet_count(&self) -> usize {
self.sheets.len()
}
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)
}
pub fn sheet_by_name(&self, name: &str) -> Option<&Worksheet> {
self.sheets.iter().find(|sheet| sheet.title == name)
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Cell {
#[serde(with = "crate::value::stored")]
pub value: Value,
#[serde(default, skip_serializing_if = "Style::is_empty")]
pub style: Style,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ColumnDimension {
pub width: Option<f64>,
pub auto_size: bool,
#[serde(default)]
pub hidden: bool,
#[serde(default)]
pub collapsed: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Hyperlink {
pub url: String,
pub tooltip: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Comment {
pub text: String,
pub author: Option<String>,
pub width: Option<u32>,
pub height: Option<u32>,
pub visible: bool,
pub fill_color: Option<String>,
}
impl Comment {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
..Self::default()
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct TextRun {
pub text: String,
#[serde(default, skip_serializing_if = "Style::is_empty")]
pub style: Style,
#[serde(default)]
pub superscript: bool,
#[serde(default)]
pub subscript: bool,
#[serde(default)]
pub plain: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChartType {
Area,
Bar,
Column,
Doughnut,
Line,
Pie,
Radar,
Scatter,
Stock,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ChartSeries {
pub name: Option<String>,
pub categories: Option<String>,
pub values: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Chart {
pub name: String,
pub kind: ChartType,
pub title: Option<String>,
pub series: Vec<ChartSeries>,
pub x_axis_title: Option<String>,
pub y_axis_title: Option<String>,
pub legend: Option<String>,
pub top_left: String,
pub bottom_right: String,
}
impl Chart {
pub fn new(name: impl Into<String>, kind: ChartType) -> Self {
Self {
name: name.into(),
kind,
title: None,
series: Vec::new(),
x_axis_title: None,
y_axis_title: None,
legend: Some("r".to_owned()),
top_left: "H7".to_owned(),
bottom_right: "P20".to_owned(),
}
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn series(mut self, name: Option<&str>, categories: Option<&str>, values: &str) -> Self {
self.series.push(ChartSeries {
name: name.map(str::to_owned),
categories: categories.map(str::to_owned),
values: values.to_owned(),
});
self
}
pub fn axis_titles(mut self, x: Option<&str>, y: Option<&str>) -> Self {
self.x_axis_title = x.map(str::to_owned);
self.y_axis_title = y.map(str::to_owned);
self
}
pub fn legend(mut self, position: Option<&str>) -> Self {
self.legend = position.map(str::to_owned);
self
}
pub fn position(mut self, top_left: impl Into<String>, bottom_right: impl Into<String>) -> Self {
self.top_left = top_left.into();
self.bottom_right = bottom_right.into();
self
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ColumnFilter {
pub filter_type: String,
pub rules: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Drawing {
pub path: String,
pub coordinates: String,
pub name: Option<String>,
pub description: Option<String>,
pub height: Option<u32>,
#[serde(default)]
pub width: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content: Option<Vec<u8>>,
pub offset_x: u32,
pub offset_y: u32,
}
impl Drawing {
pub fn new(path: impl Into<String>) -> Self {
Self {
path: path.into(),
coordinates: "A1".to_owned(),
name: None,
description: None,
height: None,
width: None,
content: None,
offset_x: 0,
offset_y: 0,
}
}
pub fn width(mut self, width: u32) -> Self {
self.width = Some(width);
self
}
pub fn content(mut self, content: Vec<u8>) -> Self {
self.content = Some(content);
self
}
pub fn coordinates(mut self, coordinates: impl Into<String>) -> Self {
self.coordinates = coordinates.into();
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn height(mut self, height: u32) -> Self {
self.height = Some(height);
self
}
pub fn offset(mut self, x: u32, y: u32) -> Self {
self.offset_x = x;
self.offset_y = y;
self
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Worksheet {
title: String,
cells: BTreeMap<u32, BTreeMap<u32, Cell>>,
column_dimensions: BTreeMap<u32, ColumnDimension>,
row_heights: BTreeMap<u32, f64>,
column_styles: BTreeMap<u32, Style>,
row_styles: BTreeMap<u32, Style>,
merges: Vec<String>,
freeze_pane: Option<String>,
tab_color: Option<String>,
protection: Option<Option<String>>,
page_breaks: Vec<u32>,
print_area: Option<String>,
auto_filter: Option<String>,
drawings: Vec<Drawing>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
hyperlinks: BTreeMap<String, Hyperlink>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
comments: BTreeMap<String, Comment>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
rich_texts: BTreeMap<String, Vec<TextRun>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
column_filters: BTreeMap<u32, ColumnFilter>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
charts: Vec<Chart>,
}
impl Worksheet {
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into(),
..Self::default()
}
}
pub fn title(&self) -> &str {
&self.title
}
pub fn set_title(&mut self, title: impl Into<String>) {
self.title = title.into();
}
pub fn get(&self, coordinate: &str) -> Result<&Value, ExcelError> {
let coordinate = Coordinate::parse(coordinate)?;
Ok(self.value_at(coordinate))
}
pub fn value_at(&self, coordinate: Coordinate) -> &Value {
static NULL: Value = Value::Null;
self.cells
.get(&coordinate.row)
.and_then(|row| row.get(&coordinate.column))
.map_or(&NULL, |cell| &cell.value)
}
pub fn cell(&self, coordinate: Coordinate) -> Option<&Cell> {
self.cells
.get(&coordinate.row)
.and_then(|row| row.get(&coordinate.column))
}
pub fn cell_exists(&self, coordinate: Coordinate) -> bool {
self.cell(coordinate).is_some()
}
pub(crate) fn cell_mut(&mut self, coordinate: Coordinate) -> &mut Cell {
self.cells
.entry(coordinate.row)
.or_default()
.entry(coordinate.column)
.or_default()
}
pub fn set(&mut self, coordinate: &str, value: impl Into<Value>) -> Result<(), ExcelError> {
let coordinate = Coordinate::parse(coordinate)?;
self.set_value_at(coordinate, value.into());
Ok(())
}
pub(crate) fn retain_cells(&mut self, mut keep: impl FnMut(Coordinate) -> bool) {
for (row, cells) in &mut self.cells {
cells.retain(|column, _| keep(Coordinate::new(*column, *row)));
}
self.cells.retain(|_, cells| !cells.is_empty());
}
pub fn set_value_at(&mut self, coordinate: Coordinate, value: Value) {
self.cell_mut(coordinate).value = value;
}
pub fn highest_row(&self) -> u32 {
self.cells.keys().next_back().copied().unwrap_or(1)
}
pub fn highest_column_index(&self) -> u32 {
self.cells
.values()
.filter_map(|row| row.keys().next_back().copied())
.max()
.unwrap_or(1)
}
pub fn highest_column(&self) -> String {
string_from_column_index(self.highest_column_index())
}
pub fn highest_column_in_row(&self, row: u32) -> String {
string_from_column_index(
self.cells
.get(&row)
.and_then(|cells| cells.keys().next_back().copied())
.unwrap_or(1),
)
}
pub fn highest_data_row(&self) -> u32 {
self.cells
.iter()
.rev()
.find(|(_, cells)| cells.values().any(|cell| !cell.value.is_null()))
.map_or(1, |(row, _)| *row)
}
pub fn highest_data_column_index(&self) -> u32 {
self.cells
.values()
.filter_map(|row| {
row.iter()
.rev()
.find(|(_, cell)| !cell.value.is_null())
.map(|(column, _)| *column)
})
.max()
.unwrap_or(1)
}
pub fn rows(&self, start: u32, end: Option<u32>, end_column: Option<u32>) -> Vec<(u32, Vec<Value>)> {
let end = end.unwrap_or_else(|| self.highest_row());
let last_column = end_column.unwrap_or_else(|| self.highest_column_index());
(start..=end)
.map(|row| {
let values = (1..=last_column)
.map(|column| self.value_at(Coordinate::new(column, row)).clone())
.collect();
(row, values)
})
.collect()
}
pub fn from_array(&mut self, rows: Vec<Vec<Value>>, start_cell: Coordinate, strict_null_comparison: bool) {
for (offset, values) in rows.into_iter().enumerate() {
let row = start_cell.row + offset as u32;
for (column_offset, value) in values.into_iter().enumerate() {
if value.is_null() && !strict_null_comparison {
continue;
}
self.set_value_at(Coordinate::new(start_cell.column + column_offset as u32, row), value);
}
}
}
pub fn apply_style(&mut self, range: &str, style: &Style) -> Result<(), ExcelError> {
match CellRange::parse(range)? {
CellRange::Columns(first, last) => {
for column in first..=last {
self.column_styles.entry(column).or_default().apply(style);
}
}
CellRange::Rows(first, last) => {
for row in first..=last {
self.row_styles.entry(row).or_default().apply(style);
}
}
CellRange::Cells(start, end) => {
for row in start.row..=end.row {
for column in start.column..=end.column {
self.cell_mut(Coordinate::new(column, row)).style.apply(style);
}
}
}
}
Ok(())
}
pub fn set_number_format(&mut self, range: &str, format: &str) -> Result<(), ExcelError> {
self.apply_style(range, &Style::new().number_format(format))
}
pub fn effective_style(&self, coordinate: Coordinate) -> Style {
let mut style = self.column_styles.get(&coordinate.column).cloned().unwrap_or_default();
if let Some(row) = self.row_styles.get(&coordinate.row) {
style.apply(row);
}
if let Some(cell) = self.cell(coordinate) {
style.apply(&cell.style);
}
style
}
pub fn column_styles(&self) -> &BTreeMap<u32, Style> {
&self.column_styles
}
pub fn row_styles(&self) -> &BTreeMap<u32, Style> {
&self.row_styles
}
pub fn cells(&self) -> impl Iterator<Item = (Coordinate, &Cell)> {
self.cells.iter().flat_map(|(row, cells)| {
cells
.iter()
.map(move |(column, cell)| (Coordinate::new(*column, *row), cell))
})
}
pub fn column_dimension(&mut self, column: &str) -> Result<&mut ColumnDimension, ExcelError> {
let index = column_index_from_string(column)?;
Ok(self.column_dimensions.entry(index).or_default())
}
pub fn column_dimensions(&self) -> &BTreeMap<u32, ColumnDimension> {
&self.column_dimensions
}
pub fn set_column_width(&mut self, column: &str, width: f64) -> Result<(), ExcelError> {
let dimension = self.column_dimension(column)?;
dimension.auto_size = false;
dimension.width = Some(width);
Ok(())
}
pub fn set_row_height(&mut self, row: u32, height: f64) {
self.row_heights.insert(row, height);
}
pub fn row_heights(&self) -> &BTreeMap<u32, f64> {
&self.row_heights
}
pub fn merge_cells(&mut self, range: &str) -> Result<(), ExcelError> {
CellRange::parse(range)?;
self.merges.push(range.to_owned());
Ok(())
}
pub fn merges(&self) -> &[String] {
&self.merges
}
pub fn freeze_pane(&mut self, cell: &str) -> Result<(), ExcelError> {
Coordinate::parse(cell)?;
self.freeze_pane = Some(cell.to_owned());
Ok(())
}
pub fn frozen_pane(&self) -> Option<&str> {
self.freeze_pane.as_deref()
}
pub fn set_tab_color(&mut self, color: impl Into<String>) {
self.tab_color = Some(color.into());
}
pub fn tab_color(&self) -> Option<&str> {
self.tab_color.as_deref()
}
pub fn protect(&mut self, password: Option<String>) {
self.protection = Some(password);
}
pub fn protection(&self) -> Option<Option<&str>> {
self.protection.as_ref().map(Option::as_deref)
}
pub fn set_row_break(&mut self, row: u32) {
if !self.page_breaks.contains(&row) {
self.page_breaks.push(row);
}
}
pub fn page_breaks(&self) -> &[u32] {
&self.page_breaks
}
pub fn set_print_area(&mut self, range: &str) -> Result<(), ExcelError> {
CellRange::parse(range)?;
self.print_area = Some(range.to_owned());
Ok(())
}
pub fn print_area(&self) -> Option<&str> {
self.print_area.as_deref()
}
pub fn set_auto_filter(&mut self, range: &str) -> Result<(), ExcelError> {
CellRange::parse(range)?;
self.auto_filter = Some(range.to_owned());
Ok(())
}
pub fn auto_filter(&self) -> Option<&str> {
self.auto_filter.as_deref()
}
pub fn add_drawing(&mut self, drawing: Drawing) {
self.drawings.push(drawing);
}
pub fn set_hyperlink(&mut self, coordinate: Coordinate, hyperlink: Hyperlink) {
self.hyperlinks.insert(coordinate.to_string(), hyperlink);
}
pub fn hyperlink(&self, coordinate: Coordinate) -> Option<&Hyperlink> {
self.hyperlinks.get(&coordinate.to_string())
}
pub fn hyperlinks(&self) -> &BTreeMap<String, Hyperlink> {
&self.hyperlinks
}
pub fn comment_mut(&mut self, coordinate: Coordinate) -> &mut Comment {
self.comments.entry(coordinate.to_string()).or_default()
}
pub fn comment(&self, coordinate: Coordinate) -> Option<&Comment> {
self.comments.get(&coordinate.to_string())
}
pub fn comments(&self) -> &BTreeMap<String, Comment> {
&self.comments
}
pub fn set_rich_text(&mut self, coordinate: Coordinate, runs: Vec<TextRun>) {
let text: String = runs.iter().map(|run| run.text.as_str()).collect();
self.set_value_at(coordinate, Value::String(text));
self.rich_texts.insert(coordinate.to_string(), runs);
}
pub fn rich_text(&self, coordinate: Coordinate) -> Option<&[TextRun]> {
self.rich_texts.get(&coordinate.to_string()).map(Vec::as_slice)
}
pub fn rich_texts(&self) -> &BTreeMap<String, Vec<TextRun>> {
&self.rich_texts
}
pub fn column_filter(&mut self, column: &str) -> Result<&mut ColumnFilter, ExcelError> {
let index = column_index_from_string(column)?;
Ok(self.column_filters.entry(index).or_default())
}
pub fn column_filters(&self) -> &BTreeMap<u32, ColumnFilter> {
&self.column_filters
}
pub fn add_chart(&mut self, chart: Chart) {
self.charts.push(chart);
}
pub fn charts(&self) -> &[Chart] {
&self.charts
}
pub fn drawings(&self) -> &[Drawing] {
&self.drawings
}
}