pub mod csv;
pub mod images;
pub mod merges;
pub mod shared_strings;
pub mod sheet_meta;
pub mod source;
pub mod stream;
pub mod styles;
pub mod workbook;
use std::path::Path;
use std::sync::Arc;
use crate::column::ColumnDef;
use crate::error::{ExcelError, Result};
use crate::header::{HeaderAnalysis, HeaderMap, HeaderOptions};
use crate::model::{DynamicRow, ExcelRow, RowData};
use crate::value::CellValue;
pub use crate::value::CellImage;
pub use csv::CsvReader;
pub use images::{
ExtractedImages, extract_all_images, extract_embedded_images, extract_images_of_sheet,
extract_wps_cellimages, parse_dispimg_id,
};
pub use merges::MergeRange;
pub use sheet_meta::{CfRule, Comment, ConditionalFormat, DataValidation, Hyperlink};
pub use shared_strings::SharedStrings;
pub use source::{EntryReader, ZipSource};
pub use stream::SheetStream;
pub use styles::{CellStyle, Styles};
pub use workbook::SheetInfo;
#[derive(Clone)]
pub struct ComputedColumn {
pub def: ColumnDef,
expr: Arc<dyn for<'a> Fn(&RowData<'a>) -> CellValue + Send + Sync>,
}
impl ComputedColumn {
pub fn new<F>(def: ColumnDef, expr: F) -> Self
where
F: for<'a> Fn(&RowData<'a>) -> CellValue + Send + Sync + 'static,
{
Self {
def,
expr: Arc::new(expr),
}
}
pub fn eval<'a>(&self, row: &RowData<'a>) -> CellValue {
(self.expr)(row)
}
pub fn header(&self) -> &str {
&self.def.header
}
}
impl std::fmt::Debug for ComputedColumn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ComputedColumn")
.field("def", &self.def)
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct RowFilter(Arc<dyn for<'a> Fn(&RowData<'a>) -> bool + Send + Sync>);
impl RowFilter {
pub fn new<F>(f: F) -> Self
where
F: for<'a> Fn(&RowData<'a>) -> bool + Send + Sync + 'static,
{
Self(Arc::new(f))
}
pub fn keep<'a>(&self, row: &RowData<'a>) -> bool {
(self.0)(row)
}
}
impl std::fmt::Debug for RowFilter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("RowFilter")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SheetSelector {
First,
Index(u32),
Name(String),
Names(Vec<String>),
All,
}
impl SheetSelector {
pub fn name(name: impl Into<String>) -> Self {
SheetSelector::Name(name.into())
}
pub fn names<I, S>(names: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
SheetSelector::Names(names.into_iter().map(Into::into).collect())
}
}
#[derive(Debug, Clone)]
pub struct ReadOptions {
pub header: HeaderOptions,
pub max_rows: Option<u64>,
pub skip_empty_rows: bool,
pub read_images: bool,
pub image_columns: Option<Vec<u16>>,
pub read_merges: bool,
pub fill_merged: bool,
pub read_hyperlinks: bool,
pub read_comments: bool,
pub read_validations: bool,
pub read_conditional_formats: bool,
pub computed: Vec<ComputedColumn>,
pub row_filter: Option<RowFilter>,
pub trim_text: bool,
}
impl Default for ReadOptions {
fn default() -> Self {
Self {
header: HeaderOptions::default(),
max_rows: None,
skip_empty_rows: true,
read_images: false,
image_columns: None,
read_merges: false,
fill_merged: true,
read_hyperlinks: false,
read_comments: false,
read_validations: false,
read_conditional_formats: false,
computed: Vec::new(),
row_filter: None,
trim_text: true,
}
}
}
impl ReadOptions {
pub fn new() -> Self {
Self::default()
}
pub fn header_options(mut self, header: HeaderOptions) -> Self {
self.header = header;
self
}
pub fn header_row(mut self, row_index: u32) -> Self {
self.header.row_index = row_index;
self
}
pub fn header_span(mut self, span: u32) -> Self {
self.header.row_span = span.max(1);
self
}
pub fn max_rows(mut self, rows: u64) -> Self {
self.max_rows = Some(rows);
self
}
pub fn with_images(mut self) -> Self {
self.read_images = true;
self
}
pub fn image_columns(mut self, cols: Vec<u16>) -> Self {
self.image_columns = Some(cols);
self
}
pub fn with_merges(mut self) -> Self {
self.read_merges = true;
self.fill_merged = true;
self
}
pub fn without_merges(mut self) -> Self {
self.read_merges = false;
self
}
pub fn merges_exposed_only(mut self) -> Self {
self.read_merges = true;
self.fill_merged = false;
self
}
pub fn with_hyperlinks(mut self) -> Self {
self.read_hyperlinks = true;
self
}
pub fn with_comments(mut self) -> Self {
self.read_comments = true;
self
}
pub fn with_validations(mut self) -> Self {
self.read_validations = true;
self
}
pub fn with_conditional_formats(mut self) -> Self {
self.read_conditional_formats = true;
self
}
pub fn computed<F>(mut self, def: ColumnDef, expr: F) -> Self
where
F: for<'a> Fn(&RowData<'a>) -> CellValue + Send + Sync + 'static,
{
self.computed.push(ComputedColumn::new(def, expr));
self
}
pub fn row_filter<F>(mut self, f: F) -> Self
where
F: for<'a> Fn(&RowData<'a>) -> bool + Send + Sync + 'static,
{
self.row_filter = Some(RowFilter::new(f));
self
}
pub fn skip_empty_rows(mut self, skip: bool) -> Self {
self.skip_empty_rows = skip;
self
}
pub fn trim_text(mut self, trim: bool) -> Self {
self.trim_text = trim;
self
}
}
pub struct ExcelReader {
source: ZipSource,
sheets: Vec<SheetInfo>,
date_1904: bool,
shared: Arc<SharedStrings>,
styles: Arc<Styles>,
}
impl ExcelReader {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
Self::from_source(ZipSource::open(path)?)
}
pub fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
Self::from_source(ZipSource::from_bytes(bytes))
}
pub fn from_source(source: ZipSource) -> Result<Self> {
let (sheets, date_1904) = workbook::load_sheets(&source)?;
let shared = match source.entry_reader("xl/sharedStrings.xml") {
Ok(reader) => SharedStrings::parse(std::io::BufReader::new(reader))?,
Err(_) => SharedStrings::empty(),
};
let styles = match source.entry_reader("xl/styles.xml") {
Ok(reader) => Styles::parse(std::io::BufReader::new(reader))?,
Err(_) => Styles::empty(),
};
Ok(Self {
source,
sheets,
date_1904,
shared: Arc::new(shared),
styles: Arc::new(styles),
})
}
pub fn source(&self) -> &ZipSource {
&self.source
}
pub fn sheets(&self) -> &[SheetInfo] {
&self.sheets
}
pub fn sheet_names(&self) -> Vec<String> {
self.sheets.iter().map(|s| s.name.clone()).collect()
}
pub fn date_1904(&self) -> bool {
self.date_1904
}
pub fn shared_strings(&self) -> &SharedStrings {
&self.shared
}
pub fn styles(&self) -> &Styles {
&self.styles
}
pub fn select(&self, selector: &SheetSelector) -> Result<Vec<&SheetInfo>> {
let found: Vec<&SheetInfo> = match selector {
SheetSelector::First => self.sheets.first().into_iter().collect(),
SheetSelector::Index(i) => self.sheets.iter().filter(|s| s.index == *i).collect(),
SheetSelector::Name(name) => self.sheets.iter().filter(|s| &s.name == name).collect(),
SheetSelector::Names(names) => names
.iter()
.map(|n| {
self.sheets
.iter()
.find(|s| &s.name == n)
.ok_or_else(|| ExcelError::SheetNotFound(n.clone()))
})
.collect::<Result<Vec<_>>>()?,
SheetSelector::All => self.sheets.iter().collect(),
};
if found.is_empty() {
return Err(ExcelError::SheetNotFound(match selector {
SheetSelector::First => "第一个工作表".to_string(),
SheetSelector::Index(i) => format!("下标 {i}"),
SheetSelector::Name(n) => n.clone(),
SheetSelector::Names(n) => n.join("、"),
SheetSelector::All => "任意工作表".to_string(),
}));
}
Ok(found)
}
pub fn stream(
&self,
selector: SheetSelector,
defs: &[ColumnDef],
options: ReadOptions,
) -> Result<SheetStream> {
let sheets = self.select(&selector)?;
let sheet = sheets[0];
self.stream_sheet(sheet, defs, options)
}
pub fn stream_sheet(
&self,
sheet: &SheetInfo,
defs: &[ColumnDef],
options: ReadOptions,
) -> Result<SheetStream> {
SheetStream::new(
self.source.clone(),
&sheet.path,
&sheet.name,
self.date_1904,
self.shared.clone(),
self.styles.clone(),
defs,
options,
)
}
pub fn analyze_header(
&self,
selector: &SheetSelector,
defs: &[ColumnDef],
options: ReadOptions,
) -> Result<HeaderAnalysis> {
let sheets = self.select(selector)?;
let mut stream = self.stream_sheet(sheets[0], defs, options)?;
let _ = stream.next_row()?;
Ok(stream
.header_analysis()
.unwrap_or_else(|| HeaderMap::dynamic(Vec::new()).analysis()))
}
pub fn analyze_all_headers(
&self,
defs: &[ColumnDef],
options: ReadOptions,
) -> Result<Vec<(String, HeaderAnalysis)>> {
let mut out = Vec::with_capacity(self.sheets.len());
for sheet in &self.sheets {
let mut stream = self.stream_sheet(sheet, defs, options.clone())?;
let _ = stream.next_row()?;
let analysis = stream
.header_analysis()
.unwrap_or_else(|| HeaderMap::dynamic(Vec::new()).analysis());
out.push((sheet.name.clone(), analysis));
}
Ok(out)
}
pub fn merge_ranges(&self, selector: &SheetSelector) -> Result<Vec<MergeRange>> {
let mut out = Vec::new();
for sheet in self.select(selector)? {
let wants = sheet_meta::MetaWants {
merges: true,
..Default::default()
};
out.extend(sheet_meta::load_sheet_meta(&self.source, &sheet.path, wants)?.merges);
}
Ok(out)
}
pub fn hyperlinks(&self, selector: &SheetSelector) -> Result<Vec<Hyperlink>> {
let mut out = Vec::new();
for sheet in self.select(selector)? {
let wants = sheet_meta::MetaWants {
hyperlinks: true,
..Default::default()
};
out.extend(sheet_meta::load_sheet_meta(&self.source, &sheet.path, wants)?.hyperlinks);
}
Ok(out)
}
pub fn validations(&self, selector: &SheetSelector) -> Result<Vec<sheet_meta::DataValidation>> {
let mut out = Vec::new();
for sheet in self.select(selector)? {
let wants = sheet_meta::MetaWants {
validations: true,
..Default::default()
};
out.extend(sheet_meta::load_sheet_meta(&self.source, &sheet.path, wants)?.validations);
}
Ok(out)
}
pub fn conditional_formats(
&self,
selector: &SheetSelector,
) -> Result<Vec<sheet_meta::ConditionalFormat>> {
let mut out = Vec::new();
for sheet in self.select(selector)? {
let wants = sheet_meta::MetaWants {
conditional_formats: true,
..Default::default()
};
out.extend(
sheet_meta::load_sheet_meta(&self.source, &sheet.path, wants)?
.conditional_formats,
);
}
Ok(out)
}
pub fn read_dynamic(
&self,
selector: &SheetSelector,
options: ReadOptions,
) -> Result<(Vec<String>, Vec<DynamicRow>)> {
let sheets = self.select(selector)?;
let mut stream = self.stream_sheet(sheets[0], &[], options)?;
let mut rows = Vec::new();
while let Some(row) = stream.next_row()? {
let dynamic = DynamicRow::from_row(&row)
.map_err(|e| ExcelError::Other(format!("动态行解析失败:{}", e.len())))?;
rows.push(dynamic);
}
let headers = stream
.header()
.map(|h| h.file_headers.clone())
.unwrap_or_default();
Ok((headers, rows))
}
pub fn comments(&self, selector: &SheetSelector) -> Result<Vec<Comment>> {
let mut out = Vec::new();
for sheet in self.select(selector)? {
out.extend(sheet_meta::load_comments(&self.source, &sheet.path)?);
}
Ok(out)
}
}