use std::fmt;
#[derive(Debug, Clone)]
pub enum ExcelError {
Io(String),
Zip(String),
Xml(String),
NotXlsx(String),
SheetNotFound(String),
MissingColumns(Vec<String>),
InvalidCell {
row: u32,
column: String,
message: String,
},
InvalidRow { row: u32, messages: Vec<String> },
Unsupported(String),
Sink(String),
Other(String),
}
impl ExcelError {
pub fn code(&self) -> &'static str {
match self {
ExcelError::Io(_) => "excel_io_failed",
ExcelError::Zip(_) => "excel_zip_failed",
ExcelError::Xml(_) => "excel_xml_failed",
ExcelError::NotXlsx(_) => "excel_not_xlsx",
ExcelError::SheetNotFound(_) => "excel_sheet_not_found",
ExcelError::MissingColumns(_) => "excel_missing_column",
ExcelError::InvalidCell { .. } => "excel_invalid_cell",
ExcelError::InvalidRow { .. } => "excel_invalid_row",
ExcelError::Unsupported(_) => "excel_unsupported",
ExcelError::Sink(_) => "excel_sink_failed",
ExcelError::Other(_) => "excel_error",
}
}
pub fn other(msg: impl Into<String>) -> Self {
ExcelError::Other(msg.into())
}
pub fn unsupported(msg: impl Into<String>) -> Self {
ExcelError::Unsupported(msg.into())
}
}
impl fmt::Display for ExcelError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ExcelError::Io(m) => write!(f, "文件读写失败:{m}"),
ExcelError::Zip(m) => write!(f, "Excel 文件损坏或格式不支持:{m}"),
ExcelError::Xml(m) => write!(f, "Excel 内部结构解析失败:{m}"),
ExcelError::NotXlsx(m) => write!(f, "不是有效的 xlsx 文件:{m}"),
ExcelError::SheetNotFound(m) => write!(f, "工作表不存在:{m}"),
ExcelError::MissingColumns(cols) => write!(f, "缺少必填列:{}", cols.join("、")),
ExcelError::InvalidCell {
row,
column,
message,
} => {
write!(f, "第 {row} 行「{column}」列:{message}")
}
ExcelError::InvalidRow { row, messages } => {
write!(f, "第 {row} 行:{}", messages.join(";"))
}
ExcelError::Unsupported(m) => write!(f, "暂不支持的 Excel 特性:{m}"),
ExcelError::Sink(m) => write!(f, "数据写入失败:{m}"),
ExcelError::Other(m) => write!(f, "{m}"),
}
}
}
impl std::error::Error for ExcelError {}
impl From<std::io::Error> for ExcelError {
fn from(e: std::io::Error) -> Self {
ExcelError::Io(e.to_string())
}
}
impl From<zip::result::ZipError> for ExcelError {
fn from(e: zip::result::ZipError) -> Self {
ExcelError::Zip(e.to_string())
}
}
impl From<quick_xml::Error> for ExcelError {
fn from(e: quick_xml::Error) -> Self {
ExcelError::Xml(e.to_string())
}
}
impl From<rust_xlsxwriter::XlsxError> for ExcelError {
fn from(e: rust_xlsxwriter::XlsxError) -> Self {
ExcelError::Other(format!("Excel 生成失败:{e}"))
}
}
impl From<serde_json::Error> for ExcelError {
fn from(e: serde_json::Error) -> Self {
ExcelError::Other(format!("JSON 序列化失败:{e}"))
}
}
impl From<chrono::ParseError> for ExcelError {
fn from(e: chrono::ParseError) -> Self {
ExcelError::Other(format!("日期解析失败:{e}"))
}
}
pub type Result<T> = std::result::Result<T, ExcelError>;