use std::fmt;
use std::sync::Arc;
use laravel::str::Str;
use crate::coordinate::{Coordinate, column_index_from_string, string_from_column_index};
use crate::error::ExcelError;
use crate::reader::ReadSheet;
use crate::row::{Key, Row};
use crate::spreadsheet::{Comment, Hyperlink as Link, Worksheet};
use crate::style::Style;
use crate::value::{Value, ValueBinder, date_time_to_excel, excel_to_date_time, format_float};
use crate::xlsx_extras::ImageContent;
pub mod formats {
pub const TEXT: &str = "@";
pub const NUMBER: &str = "0";
pub const NUMBER_00: &str = "0.00";
pub const PERCENTAGE: &str = "0%";
pub const DATE_DDMMYYYY: &str = "dd/mm/yyyy";
pub const DATE_DATETIME: &str = "d/m/yy h:mm";
pub const DATE_TIME4: &str = "h:mm:ss";
pub const ACCOUNTING_EUR: &str = "_(\"€\"* #,##0.00_);_(\"€\"* \\(#,##0.00\\);_(\"€\"* \"-\"??_);_(@_)";
pub const ACCOUNTING_USD: &str = "_(\"$\"* #,##0.00_);_(\"$\"* \\(#,##0.00\\);_(\"$\"* \"-\"??_);_(@_)";
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DataType {
String,
Numeric,
Bool,
Formula,
Inline,
Null,
}
pub const FILTER_TYPE_FILTER: &str = "filters";
pub const FILTER_TYPE_CUSTOM: &str = "customFilters";
type ValueFn = Arc<dyn Fn(&Row) -> Value + Send + Sync>;
type ReadFn = Arc<dyn Fn(Value, Coordinate) -> Value + Send + Sync>;
type TextFn = Arc<dyn Fn(&Row) -> Option<String> + Send + Sync>;
type StyleFn = Arc<dyn Fn(&mut CellStyle, &Row) + Send + Sync>;
type CommentFn = Arc<dyn Fn(&mut Comment, &Row) + Send + Sync>;
type WritingFn = Arc<dyn Fn(&mut Worksheet, Coordinate) + Send + Sync>;
#[derive(Clone)]
enum Attribute {
Key(String),
Computed(ValueFn),
}
#[derive(Clone)]
enum Dynamic {
Fixed(String),
Computed(TextFn),
}
impl Dynamic {
fn resolve(&self, row: &Row) -> Option<String> {
match self {
Self::Fixed(text) => Some(text.clone()),
Self::Computed(compute) => compute(row),
}
}
}
#[derive(Clone)]
enum Kind {
Plain,
Text,
Number,
Decimal,
Price,
Percentage {
whole_numbers: bool,
},
Date {
time: bool,
},
Boolean,
Formula {
calculate: bool,
},
Hyperlink {
url: Option<Dynamic>,
tooltip: Option<Dynamic>,
wants_url: bool,
wants_tooltip: bool,
},
RichText,
Image {
height: Option<f64>,
disk: Option<String>,
},
Enum {
valid: Option<fn(&Value) -> bool>,
},
Empty,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Position {
Next,
Key(String),
}
#[derive(Debug, Clone, Default)]
pub struct CellStyle {
style: Option<Style>,
}
impl CellStyle {
pub fn style(&mut self, style: Style) -> &mut Self {
self.style = Some(self.style.take().unwrap_or_default().merged(&style));
self
}
pub fn font(&mut self, name: &str, size: Option<f64>) -> &mut Self {
self.style(Style::new().font_name(name));
if let Some(size) = size {
self.text_size(size);
}
self
}
pub fn text_size(&mut self, size: f64) -> &mut Self {
self.style(Style::new().font_size(size))
}
pub fn bold(&mut self) -> &mut Self {
self.style(Style::new().bold())
}
pub fn italic(&mut self) -> &mut Self {
self.style(Style::new().italic())
}
}
#[derive(Debug, Clone)]
pub(crate) struct PendingImage {
pub coordinate: Coordinate,
pub path: String,
pub disk: Option<String>,
pub height: Option<f64>,
pub width: Option<f64>,
}
pub(crate) struct WriteContext<'a> {
pub binder: &'a (dyn ValueBinder + Sync),
pub images: &'a mut Vec<PendingImage>,
}
#[derive(Clone)]
pub struct Column {
title: String,
attribute: Attribute,
read_using: Option<ReadFn>,
key: Option<String>,
position: Position,
kind: Kind,
data_type: Option<DataType>,
format: Option<String>,
formatted: Option<bool>,
nullable: Option<bool>,
style: Option<Style>,
cell_styling: Option<StyleFn>,
width: Option<f64>,
auto_size: bool,
hidden: bool,
collapsed: bool,
comment: Option<Dynamic>,
comment_author: Option<String>,
comment_callback: Option<CommentFn>,
filter: Option<String>,
filter_rules: Vec<(String, Vec<String>)>,
writing: Vec<WritingFn>,
columns: Vec<Column>,
}
impl fmt::Debug for Column {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Column")
.field("title", &self.title)
.field("key", &self.get_key())
.finish_non_exhaustive()
}
}
impl Column {
fn new(title: &str, kind: Kind, data_type: Option<DataType>, format: Option<&str>) -> Self {
Self {
title: title.to_owned(),
attribute: Attribute::Key(title.snake()),
read_using: None,
key: None,
position: Position::Next,
formatted: matches!(kind, Kind::Text).then_some(true),
kind,
data_type,
format: format.map(str::to_owned),
nullable: None,
style: None,
cell_styling: None,
width: None,
auto_size: false,
hidden: false,
collapsed: false,
comment: None,
comment_author: None,
comment_callback: None,
filter: None,
filter_rules: Vec::new(),
writing: Vec::new(),
columns: Vec::new(),
}
}
#[must_use]
pub fn make(title: &str) -> Self {
Self::new(title, Kind::Plain, None, None)
}
#[must_use]
pub fn multiple(columns: impl IntoIterator<Item = Column>) -> Self {
let mut column = Self::new("", Kind::Plain, None, None);
column.attribute = Attribute::Key(String::new());
column.columns = columns.into_iter().collect();
column
}
#[must_use]
pub fn attribute(mut self, attribute: &str) -> Self {
self.attribute = Attribute::Key(if attribute.is_empty() {
self.title.snake()
} else {
attribute.to_owned()
});
self
}
#[must_use]
pub fn value(mut self, compute: impl Fn(&Row) -> Value + Send + Sync + 'static) -> Self {
self.attribute = Attribute::Computed(Arc::new(compute));
self
}
#[must_use]
pub fn read_using(mut self, read: impl Fn(Value, Coordinate) -> Value + Send + Sync + 'static) -> Self {
self.read_using = Some(Arc::new(read));
self
}
#[must_use]
pub fn key(mut self, key: &str) -> Self {
self.key = Some(key.to_owned());
self
}
#[must_use]
pub fn at(mut self, key: &str) -> Self {
self.position = Position::Key(key.to_owned());
self
}
#[must_use]
pub fn data_type(mut self, data_type: DataType) -> Self {
self.data_type = Some(data_type);
self
}
#[must_use]
pub fn format(mut self, format: &str) -> Self {
self.format = Some(format.to_owned());
self
}
#[must_use]
pub fn formatted(mut self) -> Self {
self.formatted = Some(true);
self
}
#[must_use]
pub fn nullable(mut self) -> Self {
self.nullable = Some(true);
self
}
#[must_use]
pub fn style(mut self, style: Style) -> Self {
self.style = Some(self.style.take().unwrap_or_default().merged(&style));
self
}
#[must_use]
pub fn font(self, name: &str, size: Option<f64>) -> Self {
let column = self.style(Style::new().font_name(name));
match size {
Some(size) => column.text_size(size),
None => column,
}
}
#[must_use]
pub fn text_size(self, size: f64) -> Self {
self.style(Style::new().font_size(size))
}
#[must_use]
pub fn bold(self) -> Self {
self.style(Style::new().bold())
}
#[must_use]
pub fn italic(self) -> Self {
self.style(Style::new().italic())
}
#[must_use]
pub fn with_cell_styling(mut self, styling: impl Fn(&mut CellStyle, &Row) + Send + Sync + 'static) -> Self {
self.cell_styling = Some(Arc::new(styling));
self
}
#[must_use]
pub fn width(mut self, width: f64) -> Self {
self.width = Some(width);
self
}
#[must_use]
pub fn auto_size(mut self) -> Self {
self.auto_size = true;
self
}
#[must_use]
pub fn should_auto_size(&self) -> bool {
self.auto_size
}
#[must_use]
pub fn hide(mut self) -> Self {
self.hidden = true;
self
}
#[must_use]
pub fn collapse(mut self) -> Self {
self.collapsed = true;
self
}
#[must_use]
pub fn comment(mut self, comment: &str, author: Option<&str>) -> Self {
self.comment = Some(Dynamic::Fixed(comment.to_owned()));
self.comment_author = author.map(str::to_owned);
self
}
#[must_use]
pub fn comment_using(
mut self,
comment: impl Fn(&Row) -> Option<String> + Send + Sync + 'static,
author: Option<&str>,
) -> Self {
self.comment = Some(Dynamic::Computed(Arc::new(comment)));
self.comment_author = author.map(str::to_owned);
self
}
#[must_use]
pub fn comment_callback(mut self, callback: impl Fn(&mut Comment, &Row) + Send + Sync + 'static) -> Self {
self.comment_callback = Some(Arc::new(callback));
self
}
#[must_use]
pub fn auto_filter(self) -> Self {
self.auto_filter_with(Vec::<(&str, Vec<&str>)>::new(), FILTER_TYPE_FILTER)
}
#[must_use]
pub fn auto_filter_with<'r>(
mut self,
rules: impl IntoIterator<Item = (&'r str, Vec<&'r str>)>,
filter: &str,
) -> Self {
self.filter = Some(filter.to_owned());
self.filter_rules = rules
.into_iter()
.map(|(operator, values)| (operator.to_owned(), values.into_iter().map(str::to_owned).collect()))
.collect();
self
}
#[must_use]
pub fn has_auto_filter(&self) -> bool {
self.filter.is_some()
}
#[must_use]
pub fn writing(mut self, callback: impl Fn(&mut Worksheet, Coordinate) + Send + Sync + 'static) -> Self {
self.writing.push(Arc::new(callback));
self
}
#[must_use]
pub fn title(&self) -> &str {
&self.title
}
#[must_use]
pub fn get_key(&self) -> String {
self.key.clone().unwrap_or_else(|| self.default_key())
}
#[must_use]
pub fn heading_key(&self) -> String {
self.default_key()
}
#[must_use]
pub fn is_readable(&self) -> bool {
!self.get_key().is_empty()
}
#[must_use]
pub fn has_multiple(&self) -> bool {
!self.columns.is_empty()
}
#[must_use]
pub fn needs_style_information(&self) -> bool {
match &self.kind {
Kind::RichText | Kind::Image { .. } => true,
Kind::Hyperlink {
wants_url,
wants_tooltip,
..
} => *wants_url || *wants_tooltip,
_ => self.columns.iter().any(Column::needs_style_information),
}
}
pub(crate) fn formatted_by_default(&self) -> bool {
self.formatted == Some(true) || self.columns.iter().any(Column::formatted_by_default)
}
fn default_key(&self) -> String {
match &self.attribute {
Attribute::Key(key) if !key.is_empty() => key.clone(),
_ => self.title.snake(),
}
}
fn apply_defaults(mut self, format_data: bool, nullable: bool) -> Self {
self.formatted = Some(self.formatted.unwrap_or(format_data));
self.nullable = Some(self.nullable.unwrap_or(nullable));
self.columns = self
.columns
.into_iter()
.map(|column| column.apply_defaults(format_data, nullable))
.collect();
self
}
fn sub_columns(&self) -> Vec<&Column> {
if self.has_multiple() {
self.columns.iter().collect()
} else {
vec![self]
}
}
fn write_heading(&self, worksheet: &mut Worksheet, column: u32, row: u32) {
worksheet.set_value_at(Coordinate::new(column, row), Value::String(self.title.clone()));
}
fn resolve_value(&self, row: &Row) -> Value {
match &self.attribute {
Attribute::Computed(compute) => compute(row),
Attribute::Key(key) => {
let value = data_get(row, key);
if self.nullable == Some(true) && value.is_null() {
return Value::Null;
}
self.to_excel_value(value)
}
}
}
fn to_excel_value(&self, value: Value) -> Value {
match &self.kind {
Kind::Text => Value::String(php_string(&value)),
Kind::Number => self.cast_number(&value),
Kind::Decimal => Value::Float(php_float(&value)),
Kind::Percentage { whole_numbers } => {
let number = php_float(&value);
Value::Float(if *whole_numbers { number / 100.0 } else { number })
}
Kind::Date { .. } => match value {
Value::Int(_) | Value::Float(_) => value,
other => Value::Float(string_to_excel(&php_string(&other)).unwrap_or(0.0)),
},
Kind::Boolean => Value::Bool(filter_bool(&value)),
Kind::Image { .. } => match value {
Value::String(path) => Value::String(path),
_ => Value::Null,
},
_ => value,
}
}
fn cast_number(&self, value: &Value) -> Value {
if self.format.as_deref() == Some(formats::NUMBER) {
Value::Int(php_float(value) as i64)
} else {
Value::Float(php_float(value))
}
}
pub(crate) fn write(
&self,
worksheet: &mut Worksheet,
column: u32,
row_number: u32,
row: &Row,
context: &mut WriteContext<'_>,
) -> Result<(), ExcelError> {
let coordinate = Coordinate::new(column, row_number);
let value = self.resolve_value(row);
self.write_value(worksheet, coordinate, value, row, context)?;
self.write_cell_style(worksheet, coordinate, row)?;
self.write_comment(worksheet, coordinate, row);
Ok(())
}
fn write_value(
&self,
worksheet: &mut Worksheet,
coordinate: Coordinate,
value: Value,
row: &Row,
context: &mut WriteContext<'_>,
) -> Result<(), ExcelError> {
if let Kind::Image { height, disk } = &self.kind {
if let Value::String(path) = value {
context.images.push(PendingImage {
coordinate,
path,
disk: disk.clone(),
height: *height,
width: self.width,
});
}
return Ok(());
}
if value.is_null() && self.nullable == Some(true) {
worksheet.set_value_at(coordinate, Value::Null);
} else if let Some(data_type) = self.data_type {
match data_type {
DataType::Inline => worksheet.set_rich_text(
coordinate,
crate::rich_text::from_html(&format!("<div>{}</div>", php_string(&value))),
),
other => worksheet.set_value_at(coordinate, explicit(value, other)?),
}
} else {
let (bound, format) = context.binder.bind_value_with_format(coordinate, value);
worksheet.set_value_at(coordinate, bound);
if let Some(format) = format {
worksheet.set_number_format(&coordinate.to_string(), &format)?;
}
}
if let Kind::Hyperlink { url, tooltip, .. } = &self.kind {
let text = php_string(worksheet.value_at(coordinate));
let url = url
.as_ref()
.and_then(|url| url.resolve(row))
.filter(|url| !url.is_empty());
let tooltip = tooltip
.as_ref()
.and_then(|tooltip| tooltip.resolve(row))
.filter(|tooltip| !tooltip.is_empty());
let link = url.clone().unwrap_or_else(|| text.clone());
let tip = tooltip.or(url).unwrap_or(text);
if !link.is_empty() {
worksheet.set_hyperlink(
coordinate,
Link {
url: link,
tooltip: Some(tip),
},
);
}
}
for callback in &self.writing {
callback(worksheet, coordinate);
}
Ok(())
}
fn write_cell_style(&self, worksheet: &mut Worksheet, coordinate: Coordinate, row: &Row) -> Result<(), ExcelError> {
let Some(styling) = &self.cell_styling else {
return Ok(());
};
let mut style = CellStyle::default();
styling(&mut style, row);
if let Some(style) = style.style {
worksheet.apply_style(&coordinate.to_string(), &style)?;
}
Ok(())
}
fn write_comment(&self, worksheet: &mut Worksheet, coordinate: Coordinate, row: &Row) {
let Some(comment) = &self.comment else { return };
let Some(text) = comment.resolve(row).filter(|text| !text.is_empty()) else {
return;
};
let cell_comment = worksheet.comment_mut(coordinate);
cell_comment.text.push_str(&text);
if let Some(author) = &self.comment_author {
cell_comment.author = Some(author.clone());
}
if let Some(callback) = &self.comment_callback {
callback(cell_comment, row);
}
}
fn after_writing(&self, worksheet: &mut Worksheet, column: u32, first_data_row: u32) -> Result<(), ExcelError> {
let letter = string_from_column_index(column);
let highest = worksheet.highest_row();
let range = (highest >= first_data_row).then(|| format!("{letter}{first_data_row}:{letter}{highest}"));
if let (Some(format), Some(range)) = (&self.format, &range) {
worksheet.set_number_format(range, format)?;
}
if let (Some(style), Some(range)) = (&self.style, &range) {
worksheet.apply_style(range, style)?;
}
let dimension = worksheet.column_dimension(&letter)?;
if let Some(width) = self.width {
dimension.width = Some(width);
}
if self.hidden {
dimension.hidden = true;
}
if self.collapsed {
dimension.collapsed = true;
}
if self.auto_size {
dimension.auto_size = true;
}
if let Some(filter) = &self.filter
&& !(filter == FILTER_TYPE_FILTER && self.filter_rules.is_empty())
{
let column_filter = worksheet.column_filter(&letter)?;
column_filter.filter_type = filter.clone();
for (operator, values) in &self.filter_rules {
for value in values {
column_filter.rules.push((operator.clone(), value.clone()));
}
}
}
Ok(())
}
fn read(&self, sheet: &ReadSheet, coordinate: Coordinate, images: &mut Vec<(String, ImageContent)>) -> Value {
match &self.kind {
Kind::Empty => return Value::Null,
Kind::Formula { calculate } => return sheet.value(coordinate, *calculate),
Kind::RichText => {
return Value::String(match sheet.worksheet.rich_text(coordinate) {
Some(runs) => crate::rich_text::to_html(runs),
None => escape(&php_string(&sheet.value(coordinate, false))),
});
}
_ => {}
}
let value = self.read_value(sheet, coordinate, images);
if self.nullable == Some(true) && blank(&value) {
return Value::Null;
}
let value = self.cast(value);
match &self.read_using {
Some(read) => read(value, coordinate),
None => value,
}
}
fn read_value(&self, sheet: &ReadSheet, coordinate: Coordinate, images: &mut Vec<(String, ImageContent)>) -> Value {
match &self.kind {
Kind::Hyperlink { wants_url: true, .. } => {
return sheet
.worksheet
.hyperlink(coordinate)
.map_or(Value::Null, |link| Value::String(link.url.clone()));
}
Kind::Hyperlink {
wants_tooltip: true, ..
} => {
return sheet
.worksheet
.hyperlink(coordinate)
.and_then(|link| link.tooltip.clone())
.map_or(Value::Null, Value::String);
}
Kind::Image { .. } => {
let coordinates = coordinate.to_string();
return match sheet.images.iter().find(|image| image.coordinates == coordinates) {
Some(image) => {
images.push((self.get_key(), image.clone()));
Value::String(image.filename.clone())
}
None => Value::Null,
};
}
_ => {}
}
if self.formatted == Some(true) {
return sheet.formatted(coordinate, true, self.format.as_deref());
}
sheet.value(coordinate, true)
}
fn cast(&self, value: Value) -> Value {
match &self.kind {
Kind::Text => Value::String(php_string(&value)),
Kind::Number => self.cast_number(&value),
Kind::Decimal => Value::Float(php_float(&value)),
Kind::Percentage { whole_numbers } => {
let number = php_float(&value);
Value::Float(if *whole_numbers { number * 100.0 } else { number })
}
Kind::Date { time } => {
let date = excel_to_date_time(php_float(&value));
let text = if *time {
date.strftime("%Y-%m-%d %H:%M:%S").to_string()
} else {
date.strftime("%Y-%m-%d 00:00:00").to_string()
};
Value::String(text)
}
Kind::Boolean => Value::Bool(filter_bool(&value)),
Kind::Enum { valid: Some(valid) } => {
if valid(&value) {
value
} else {
Value::Null
}
}
_ => value,
}
}
}
fn explicit(value: Value, data_type: DataType) -> Result<Value, ExcelError> {
Ok(match data_type {
DataType::String => Value::String(php_string(&value)),
DataType::Numeric => match value {
Value::Int(_) | Value::Float(_) => value,
Value::Null => Value::Int(0),
Value::Bool(value) => Value::Int(i64::from(value)),
Value::String(text) => match numeric(&text) {
Some(number) => number,
None => {
return Err(ExcelError::Write(
"Invalid numeric value for datatype Numeric".to_owned(),
));
}
},
other => {
return Err(ExcelError::Write(format!(
"Invalid numeric value for datatype Numeric: {other}"
)));
}
},
DataType::Bool => Value::Bool(match value {
Value::Bool(value) => value,
Value::Null => false,
Value::Int(number) => number != 0,
Value::Float(number) => number != 0.0,
Value::String(text) => !(text.is_empty() || text == "0"),
_ => true,
}),
DataType::Formula => match value {
Value::Formula(formula) => Value::Formula(formula),
other => {
let text = php_string(&other);
Value::Formula(text.strip_prefix('=').unwrap_or(&text).to_owned())
}
},
DataType::Null => Value::Null,
DataType::Inline => Value::String(php_string(&value)),
})
}
fn numeric(text: &str) -> Option<Value> {
let trimmed = text.trim();
if let Ok(number) = trimmed.parse::<i64>() {
return Some(Value::Int(number));
}
trimmed
.parse::<f64>()
.ok()
.filter(|number| number.is_finite())
.map(Value::Float)
}
fn data_get(row: &Row, key: &str) -> Value {
if let Some(value) = row.get(Key::from(key)) {
return value.clone();
}
let mut segments = key.split('.');
let Some(first) = segments.next() else {
return Value::Null;
};
let mut value = match row.get(Key::from(first)) {
Some(value) => value.clone(),
None => match first.parse::<usize>() {
Ok(index) => row.get(index).cloned().unwrap_or_default(),
Err(_) => return Value::Null,
},
};
for segment in segments {
value = match value {
Value::Array(items) => match segment.parse::<usize>() {
Ok(index) => items.get(index).cloned().unwrap_or_default(),
Err(_) => return Value::Null,
},
_ => return Value::Null,
};
}
value
}
fn php_string(value: &Value) -> String {
match value {
Value::Null | Value::Bool(false) => String::new(),
Value::Bool(true) => "1".to_owned(),
Value::Float(number) => format_float(*number),
Value::Formula(formula) => format!("={formula}"),
other => other.to_text(),
}
}
fn php_float(value: &Value) -> f64 {
match value {
Value::Int(number) => *number as f64,
Value::Float(number) => *number,
Value::Bool(true) => 1.0,
Value::String(text) => {
let text = text.trim_start();
let bytes = text.as_bytes();
let mut end = 0;
let mut seen_digit = false;
let mut seen_dot = false;
let mut seen_exponent = false;
while end < bytes.len() {
let ok = match bytes[end] {
b'0'..=b'9' => {
seen_digit = true;
true
}
b'+' | b'-' => end == 0 || matches!(bytes[end - 1], b'e' | b'E'),
b'.' if !seen_dot && !seen_exponent => {
seen_dot = true;
true
}
b'e' | b'E' if seen_digit && !seen_exponent => {
seen_exponent = true;
true
}
_ => false,
};
if !ok {
break;
}
end += 1;
}
let mut candidate = &text[..end];
while !candidate.is_empty() && candidate.parse::<f64>().is_err() {
candidate = &candidate[..candidate.len() - 1];
}
candidate.parse().unwrap_or(0.0)
}
_ => 0.0,
}
}
fn filter_bool(value: &Value) -> bool {
match value {
Value::Bool(value) => *value,
Value::Int(number) => *number == 1,
Value::Float(number) => *number == 1.0,
Value::String(text) => matches!(text.trim().to_lowercase().as_str(), "1" | "true" | "on" | "yes"),
_ => false,
}
}
fn blank(value: &Value) -> bool {
match value {
Value::Null => true,
Value::String(text) => text.trim().is_empty(),
Value::Array(values) => values.is_empty(),
_ => false,
}
}
fn escape(text: &str) -> String {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
fn string_to_excel(text: &str) -> Option<f64> {
use laravel::time::civil::{Date, Time};
let text = text.trim();
if text.is_empty() {
return None;
}
let (date_part, time_part) = match text.split_once(['T', ' ']) {
Some((date, time)) => (Some(date), Some(time)),
None if text.contains(':') => (None, Some(text)),
None => (Some(text), None),
};
let time = match time_part {
Some(time) => {
let time = time.trim_end_matches('Z');
let time = time.split('+').next().unwrap_or(time);
let mut parts = time.split(':');
let hour: i8 = parts.next()?.trim().parse().ok()?;
let minute: i8 = parts.next().unwrap_or("0").trim().parse().ok()?;
let second: f64 = parts.next().unwrap_or("0").trim().parse().ok()?;
Time::new(hour, minute, second.trunc() as i8, 0).ok()?
}
None => Time::midnight(),
};
let Some(date_part) = date_part else {
let seconds = f64::from(time.hour()) * 3600.0 + f64::from(time.minute()) * 60.0 + f64::from(time.second());
return Some(seconds / 86_400.0);
};
let date = if let Some((year, rest)) = date_part.split_once('-') {
let (month, day) = rest.split_once('-')?;
Date::new(year.parse().ok()?, month.parse().ok()?, day.parse().ok()?).ok()?
} else if let Some((month, rest)) = date_part.split_once('/') {
let (day, year) = rest.split_once('/')?;
Date::new(year.parse().ok()?, month.parse().ok()?, day.parse().ok()?).ok()?
} else {
return None;
};
Some(date_time_to_excel(date.to_datetime(time)))
}
macro_rules! column_type {
($(#[$doc:meta])* $name:ident, $kind:expr, $data_type:expr, $format:expr) => {
$(#[$doc])*
#[derive(Debug, Clone, Copy)]
pub struct $name;
impl $name {
#[must_use]
pub fn make(title: &str) -> Column {
Column::new(title, $kind, $data_type, $format)
}
}
};
}
column_type!(
Text,
Kind::Text,
Some(DataType::String),
Some(formats::TEXT)
);
column_type!(
Number,
Kind::Number,
Some(DataType::Numeric),
Some(formats::NUMBER)
);
column_type!(
Decimal,
Kind::Decimal,
Some(DataType::Numeric),
Some(formats::NUMBER_00)
);
column_type!(
Price,
Kind::Price,
Some(DataType::Numeric),
Some(formats::NUMBER)
);
column_type!(
Percentage,
Kind::Percentage { whole_numbers: false },
Some(DataType::Numeric),
Some(formats::PERCENTAGE)
);
column_type!(
Date,
Kind::Date { time: false },
Some(DataType::Numeric),
Some(formats::DATE_DDMMYYYY)
);
column_type!(
DateTime,
Kind::Date { time: true },
Some(DataType::Numeric),
Some(formats::DATE_DATETIME)
);
column_type!(
Time,
Kind::Date { time: true },
Some(DataType::Numeric),
Some(formats::DATE_TIME4)
);
column_type!(
Boolean,
Kind::Boolean,
Some(DataType::Bool),
None
);
column_type!(
Formula,
Kind::Formula { calculate: false },
Some(DataType::Formula),
None
);
column_type!(
Hyperlink,
Kind::Hyperlink {
url: None,
tooltip: None,
wants_url: false,
wants_tooltip: false
},
None,
None
);
column_type!(
RichText,
Kind::RichText,
Some(DataType::Inline),
None
);
column_type!(
Image,
Kind::Image {
height: None,
disk: None
},
None,
None
);
column_type!(
Enum,
Kind::Enum { valid: None },
None,
None
);
#[derive(Debug, Clone, Copy)]
pub struct EmptyCell;
impl EmptyCell {
#[must_use]
pub fn make(title: Option<&str>) -> Column {
Column::new(title.unwrap_or_default(), Kind::Empty, Some(DataType::Null), None)
}
}
impl Column {
#[must_use]
pub fn with_decimals(self) -> Self {
self.format(formats::NUMBER_00)
}
#[must_use]
pub fn currency(self, format: &str) -> Self {
self.format(format)
}
#[must_use]
pub fn in_euros(self) -> Self {
self.currency(formats::ACCOUNTING_EUR)
}
#[must_use]
pub fn in_dollars(self) -> Self {
self.currency(formats::ACCOUNTING_USD)
}
#[must_use]
pub fn from_whole_numbers(mut self) -> Self {
if let Kind::Percentage { whole_numbers } = &mut self.kind {
*whole_numbers = true;
}
self
}
#[must_use]
pub fn calculated(mut self) -> Self {
if let Kind::Formula { calculate } = &mut self.kind {
*calculate = true;
}
self
}
#[must_use]
pub fn url(mut self, url: &str) -> Self {
if let Kind::Hyperlink { url: slot, .. } = &mut self.kind {
*slot = Some(Dynamic::Fixed(url.to_owned()));
}
self
}
#[must_use]
pub fn url_using(mut self, url: impl Fn(&Row) -> Option<String> + Send + Sync + 'static) -> Self {
if let Kind::Hyperlink { url: slot, .. } = &mut self.kind {
*slot = Some(Dynamic::Computed(Arc::new(url)));
}
self
}
#[must_use]
pub fn read_url(mut self) -> Self {
if let Kind::Hyperlink { wants_url, .. } = &mut self.kind {
*wants_url = true;
}
self
}
#[must_use]
pub fn tooltip(mut self, tooltip: &str) -> Self {
if let Kind::Hyperlink { tooltip: slot, .. } = &mut self.kind {
*slot = Some(Dynamic::Fixed(tooltip.to_owned()));
}
self
}
#[must_use]
pub fn tooltip_using(mut self, tooltip: impl Fn(&Row) -> Option<String> + Send + Sync + 'static) -> Self {
if let Kind::Hyperlink { tooltip: slot, .. } = &mut self.kind {
*slot = Some(Dynamic::Computed(Arc::new(tooltip)));
}
self
}
#[must_use]
pub fn read_tooltip(mut self) -> Self {
if let Kind::Hyperlink { wants_tooltip, .. } = &mut self.kind {
*wants_tooltip = true;
}
self
}
#[must_use]
pub fn height(mut self, height: f64) -> Self {
if let Kind::Image { height: slot, .. } = &mut self.kind {
*slot = Some(height);
}
self
}
#[must_use]
pub fn disk(mut self, disk: &str) -> Self {
if let Kind::Image { disk: slot, .. } = &mut self.kind {
*slot = Some(disk.to_owned());
}
self
}
#[must_use]
pub fn of<T: serde::de::DeserializeOwned>(mut self) -> Self {
if let Kind::Enum { valid } = &mut self.kind {
*valid = Some(|value: &Value| serde_json::from_value::<T>(value.to_json()).is_ok());
}
self
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct ColumnCollection {
columns: Vec<(u32, Column)>,
unmatched: Vec<String>,
}
impl ColumnCollection {
pub(crate) fn make(
columns: Vec<Column>,
heading_row: Option<&[String]>,
offset: u32,
format_data: bool,
nullable: bool,
) -> Result<Self, ExcelError> {
let mut collection = Self::default();
let mut index = 0;
for column in columns {
let column = column.apply_defaults(format_data, nullable);
index += 1;
let number = match (heading_row, &column.position) {
(Some(headings), position) => {
let heading = match position {
Position::Key(key) => key.clone(),
Position::Next => column.heading_key(),
};
match headings.iter().position(|candidate| *candidate == heading) {
Some(position) => position as u32 + 1,
None => {
let key = column.get_key();
if !collection.unmatched.contains(&key) {
collection.unmatched.push(key);
}
continue;
}
}
}
(None, Position::Key(letter)) => column_index_from_string(letter)?,
(None, Position::Next) => index + offset,
};
if collection.columns.iter().any(|(existing, _)| *existing == number) {
return Err(ExcelError::ColumnCollision(string_from_column_index(number)));
}
collection.columns.push((number, column));
}
collection.columns.sort_by_key(|(number, _)| *number);
Ok(collection)
}
pub(crate) fn has_multiple(&self) -> bool {
self.columns.iter().any(|(_, column)| column.has_multiple())
}
pub(crate) fn write_headings(&self, worksheet: &mut Worksheet, row: u32) {
for (number, column) in &self.columns {
column.write_heading(worksheet, *number, row);
}
}
pub(crate) fn write_row(
&self,
worksheet: &mut Worksheet,
row_number: u32,
row: &Row,
context: &mut WriteContext<'_>,
) -> Result<(), ExcelError> {
for (number, column) in &self.columns {
column.write(worksheet, *number, row_number, row, context)?;
}
Ok(())
}
pub(crate) fn after_writing(&self, worksheet: &mut Worksheet, heading_row: u32) -> Result<(), ExcelError> {
let filtered: Vec<u32> = self
.columns
.iter()
.filter(|(_, column)| column.has_auto_filter())
.map(|(number, _)| *number)
.collect();
if let (Some(first), Some(last)) = (filtered.first(), filtered.last()) {
let range = format!(
"{}{heading_row}:{}{}",
string_from_column_index(*first),
string_from_column_index(*last),
worksheet.highest_row()
);
worksheet.set_auto_filter(&range)?;
}
for (number, column) in &self.columns {
column.after_writing(worksheet, *number, heading_row + 1)?;
}
Ok(())
}
pub(crate) fn read_row(&self, sheet: &ReadSheet, row_number: u32) -> Row {
let mut row = Row::new();
for key in &self.unmatched {
row.insert(key.clone(), Value::Null);
}
let mut images = Vec::new();
for (number, column) in &self.columns {
let coordinate = Coordinate::new(*number, row_number);
for part in column.sub_columns() {
if part.is_readable() {
let value = part.read(sheet, coordinate, &mut images);
row.insert(part.get_key(), value);
}
}
}
for (key, image) in images {
row.set_image(key, image);
}
row.with_number(row_number)
}
}
pub(crate) fn requires_style_information(columns: &[Column]) -> bool {
columns.iter().any(Column::needs_style_information)
}