use serde::Serialize;
use crate::column::ColumnDef;
use crate::header::{HeaderMap, excel_column_name};
use crate::read::merges::MergeRange;
use crate::read::sheet_meta::{Comment, ConditionalFormat, DataValidation, Hyperlink};
use crate::read::styles::{CellStyle, Styles};
use crate::value::{Cell, CellImage, CellValue, FromCell, IntoCell};
#[derive(Debug, Clone, PartialEq)]
pub struct RowImage {
pub column: u16,
pub header: String,
pub bytes: Vec<u8>,
pub ext: String,
pub name: Option<String>,
}
impl RowImage {
pub fn mime(&self) -> &'static str {
crate::value::mime_from_ext(&self.ext)
}
pub fn image(&self) -> CellImage {
CellImage {
bytes: self.bytes.clone(),
ext: self.ext.clone(),
name: self.name.clone(),
}
}
pub fn len(&self) -> usize {
self.bytes.len()
}
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ColumnError {
pub column: String,
pub file_header: String,
pub message: String,
}
impl ColumnError {
pub fn new(column: impl Into<String>, message: impl Into<String>) -> Self {
Self {
column: column.into(),
file_header: String::new(),
message: message.into(),
}
}
}
pub struct RowData<'a> {
pub row_index: u32,
pub sheet: &'a str,
pub header: &'a HeaderMap,
pub cells: &'a [Cell],
pub images: &'a [RowImage],
pub merges: &'a [MergeRange],
pub styles: &'a Styles,
pub hyperlinks: &'a [Hyperlink],
pub comments: &'a [Comment],
pub validations: &'a [DataValidation],
pub conditional_formats: &'a [ConditionalFormat],
}
impl<'a> RowData<'a> {
pub fn cell_at(&self, col: u16) -> Option<&Cell> {
self.cells.iter().find(|c| c.col == col)
}
pub fn cell_of(&self, header: &str) -> Option<&Cell> {
let col = self.header.index_of(header)?;
self.cell_at(col)
}
pub fn value_of(&self, header: &str) -> Option<&CellValue> {
self.cell_of(header).map(|c| &c.value)
}
pub fn text_of(&self, header: &str) -> String {
self.cell_of(header).map(|c| c.text()).unwrap_or_default()
}
pub fn get<T: FromCell>(&self, header: &str) -> Result<T, String> {
match self.cell_of(header) {
Some(c) => T::from_cell(c),
None => Err(format!("缺少列「{}」", header)),
}
}
pub fn opt<T: FromCell>(&self, header: &str) -> Result<Option<T>, String> {
match self.cell_of(header) {
Some(c) if !c.value.is_empty() => T::from_cell(c).map(Some),
_ => Ok(None),
}
}
pub fn string(&self, header: &str) -> Option<String> {
let cell = self.cell_of(header)?;
if cell.value.is_empty() {
None
} else {
Some(cell.text())
}
}
pub fn images_of(&self, header: &str) -> Vec<&RowImage> {
let Some(col) = self.header.index_of(header) else {
return Vec::new();
};
self.images.iter().filter(|i| i.column == col).collect()
}
pub fn image_at(&self, n: usize) -> Option<&RowImage> {
self.images.get(n)
}
pub fn merged_at(&self, col: u16) -> Option<&MergeRange> {
self.merges
.iter()
.find(|m| col >= m.first_col && col <= m.last_col)
}
pub fn cell_style(&self, header: &str) -> Option<CellStyle> {
let col = self.header.index_of(header)?;
self.style_at(col)
}
pub fn style_at(&self, col: u16) -> Option<CellStyle> {
self.cell_at(col).map(|c| self.styles.cell_style(c.style))
}
pub fn link_at(&self, col: u16) -> Option<&Hyperlink> {
self.hyperlinks
.iter()
.find(|h| h.row == self.row_index && h.col == col)
}
pub fn comment_at(&self, col: u16) -> Option<&Comment> {
self.comments
.iter()
.find(|c| c.row == self.row_index && c.col == col)
}
pub fn validation_at(&self, col: u16) -> Option<&DataValidation> {
self.validations
.iter()
.find(|v| v.contains(self.row_index, col))
}
pub fn conditional_format_at(&self, col: u16) -> Option<&ConditionalFormat> {
self.conditional_formats
.iter()
.find(|cf| cf.contains(self.row_index, col))
}
pub fn link_of(&self, header: &str) -> Option<&str> {
self.link_at(self.header.index_of(header)?)?.href()
}
pub fn comment_of(&self, header: &str) -> Option<&str> {
Some(self.comment_at(self.header.index_of(header)?)?.text.as_str())
}
pub fn is_empty(&self) -> bool {
if !self.images.is_empty() {
return false;
}
self.cells.iter().all(|c| c.value.is_empty())
}
pub fn to_text_row(&self) -> Vec<String> {
(0..self.header.file_headers.len() as u16)
.map(|col| self.cell_at(col).map(|c| c.text()).unwrap_or_default())
.collect()
}
pub fn missing_columns(&self) -> Vec<String> {
self.header
.columns
.iter()
.filter(|c| !c.is_matched())
.map(|c| c.header.clone())
.collect()
}
}
pub trait ExcelRow: Sized + Send + 'static {
fn columns() -> Vec<ColumnDef>;
fn from_row(row: &RowData<'_>) -> Result<Self, Vec<ColumnError>>;
fn to_row(&self) -> Vec<CellValue>;
fn sheet_name() -> Option<&'static str> {
None
}
fn validate(&self) -> Result<(), Vec<String>> {
Ok(())
}
}
#[derive(Debug, Clone, Default)]
pub struct DynamicRow {
pub entries: Vec<(String, CellValue)>,
}
impl DynamicRow {
pub fn get(&self, header: &str) -> Option<&CellValue> {
self.entries
.iter()
.find(|(h, _)| h == header)
.map(|(_, v)| v)
}
pub fn text(&self, header: &str) -> String {
self.get(header).map(|v| v.to_text()).unwrap_or_default()
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn headers(&self) -> Vec<String> {
self.entries.iter().map(|(h, _)| h.clone()).collect()
}
}
impl ExcelRow for DynamicRow {
fn columns() -> Vec<ColumnDef> {
Vec::new()
}
fn from_row(row: &RowData<'_>) -> Result<Self, Vec<ColumnError>> {
let entries = row
.header
.file_headers
.iter()
.enumerate()
.map(|(i, h)| {
let v = row
.cell_at(i as u16)
.map(|c| c.value.clone())
.unwrap_or(CellValue::Empty);
(h.clone(), v)
})
.collect();
Ok(DynamicRow { entries })
}
fn to_row(&self) -> Vec<CellValue> {
self.entries.iter().map(|(_, v)| v.clone()).collect()
}
}
pub fn values_of<T: IntoCell>(items: &[T]) -> Vec<CellValue> {
items.iter().map(|v| v.into_cell()).collect()
}
pub fn excel_column_of(index: u16) -> String {
excel_column_name(index)
}