Skip to main content

fast_excel/
model.rs

1//! 行模型与声明式映射
2//!
3//! 业务侧只需要:`#[derive(ExcelRow)] struct XxxRow { ... }`(或手写 [`ExcelRow`]),
4//! 工具就能按表头把 Excel 行映射成结构体,并反向写出。
5
6use serde::Serialize;
7
8use crate::column::ColumnDef;
9use crate::header::{HeaderMap, excel_column_name};
10use crate::read::merges::MergeRange;
11use crate::read::sheet_meta::{Comment, ConditionalFormat, DataValidation, Hyperlink};
12use crate::read::styles::{CellStyle, Styles};
13use crate::value::{Cell, CellImage, CellValue, FromCell, IntoCell};
14
15/// 行内图片:导入时按"行 + 列"对应到具体单元格
16#[derive(Debug, Clone, PartialEq)]
17pub struct RowImage {
18    /// 所在列(0 基)
19    pub column: u16,
20    /// 该列对应的表头(已按声明列归一,取不到时用文件表头)
21    pub header: String,
22    pub bytes: Vec<u8>,
23    /// 扩展名(小写,不带点)
24    pub ext: String,
25    /// 原始名 / 占位名
26    pub name: Option<String>,
27}
28
29impl RowImage {
30    pub fn mime(&self) -> &'static str {
31        crate::value::mime_from_ext(&self.ext)
32    }
33
34    pub fn image(&self) -> CellImage {
35        CellImage {
36            bytes: self.bytes.clone(),
37            ext: self.ext.clone(),
38            name: self.name.clone(),
39        }
40    }
41
42    /// 识别到的图片数量
43    pub fn len(&self) -> usize {
44        self.bytes.len()
45    }
46
47    pub fn is_empty(&self) -> bool {
48        self.bytes.is_empty()
49    }
50}
51
52/// 单元格错误(列级)
53#[derive(Debug, Clone, Serialize)]
54#[serde(rename_all = "camelCase")]
55pub struct ColumnError {
56    /// 模型列名(标准表头)
57    pub column: String,
58    /// 文件里的实际表头(缺失时为空)
59    pub file_header: String,
60    pub message: String,
61}
62
63impl ColumnError {
64    pub fn new(column: impl Into<String>, message: impl Into<String>) -> Self {
65        Self {
66            column: column.into(),
67            file_header: String::new(),
68            message: message.into(),
69        }
70    }
71}
72
73/// 一行原始数据(解析后、映射前)
74pub struct RowData<'a> {
75    /// Excel 行号(1 基)
76    pub row_index: u32,
77    /// 工作表名
78    pub sheet: &'a str,
79    /// 表头解析结果(含列序对应关系)
80    pub header: &'a HeaderMap,
81    /// 本行单元格(可能稀疏:空单元格不出现)
82    pub cells: &'a [Cell],
83    /// 本行图片(仅当开启读图)
84    pub images: &'a [RowImage],
85    /// 与本行相交的合并区域(仅当开启合并读取;见 [`crate::ReadOptions::with_merges`])
86    pub merges: &'a [MergeRange],
87    /// 单元格样式表(判断字体颜色 / 底色 / 加粗 / 斜体)
88    pub styles: &'a Styles,
89    /// 本工作表的超链接(仅当 [`crate::ReadOptions::with_hyperlinks`] 开启时非空)
90    pub hyperlinks: &'a [Hyperlink],
91    /// 本工作表的批注(仅当 [`crate::ReadOptions::with_comments`] 开启时非空)
92    pub comments: &'a [Comment],
93    /// 本工作表的数据验证(仅当 [`crate::ReadOptions::with_validations`] 开启时非空)
94    pub validations: &'a [DataValidation],
95    /// 本工作表的条件格式(仅当 [`crate::ReadOptions::with_conditional_formats`] 开启时非空)
96    pub conditional_formats: &'a [ConditionalFormat],
97}
98
99impl<'a> RowData<'a> {
100    /// 按列索引取单元格
101    pub fn cell_at(&self, col: u16) -> Option<&Cell> {
102        self.cells.iter().find(|c| c.col == col)
103    }
104
105    /// 按模型列名(或别名)取单元格
106    pub fn cell_of(&self, header: &str) -> Option<&Cell> {
107        let col = self.header.index_of(header)?;
108        self.cell_at(col)
109    }
110
111    pub fn value_of(&self, header: &str) -> Option<&CellValue> {
112        self.cell_of(header).map(|c| &c.value)
113    }
114
115    pub fn text_of(&self, header: &str) -> String {
116        self.cell_of(header).map(|c| c.text()).unwrap_or_default()
117    }
118
119    /// 取强类型值(列缺失或空值都会报错,用于必填字段)
120    pub fn get<T: FromCell>(&self, header: &str) -> Result<T, String> {
121        match self.cell_of(header) {
122            Some(c) => T::from_cell(c),
123            None => Err(format!("缺少列「{}」", header)),
124        }
125    }
126
127    /// 取可选值(列缺失或空值都返回 `None`)
128    pub fn opt<T: FromCell>(&self, header: &str) -> Result<Option<T>, String> {
129        match self.cell_of(header) {
130            Some(c) if !c.value.is_empty() => T::from_cell(c).map(Some),
131            _ => Ok(None),
132        }
133    }
134
135    /// 取字符串(保持"列缺失"与"空值"都为空串)
136    pub fn string(&self, header: &str) -> Option<String> {
137        let cell = self.cell_of(header)?;
138        if cell.value.is_empty() {
139            None
140        } else {
141            Some(cell.text())
142        }
143    }
144
145    /// 该列对应的行内图片(按列筛)
146    pub fn images_of(&self, header: &str) -> Vec<&RowImage> {
147        let Some(col) = self.header.index_of(header) else {
148            return Vec::new();
149        };
150        self.images.iter().filter(|i| i.column == col).collect()
151    }
152
153    /// 第 n 张图片(图片列:图片1/图片2… 按列升序)
154    pub fn image_at(&self, n: usize) -> Option<&RowImage> {
155        self.images.get(n)
156    }
157
158    /// 本行是否落在某个合并区域内(返回该区域)
159    pub fn merged_at(&self, col: u16) -> Option<&MergeRange> {
160        self.merges
161            .iter()
162            .find(|m| col >= m.first_col && col <= m.last_col)
163    }
164
165    /// 某列的样式(底色 / 字体颜色 / 加粗 / 斜体);列不存在返回 `None`
166    pub fn cell_style(&self, header: &str) -> Option<CellStyle> {
167        let col = self.header.index_of(header)?;
168        self.style_at(col)
169    }
170
171    /// 按文件列索引取样式
172    pub fn style_at(&self, col: u16) -> Option<CellStyle> {
173        self.cell_at(col).map(|c| self.styles.cell_style(c.style))
174    }
175
176    /// 某列的超链接
177    pub fn link_at(&self, col: u16) -> Option<&Hyperlink> {
178        self.hyperlinks
179            .iter()
180            .find(|h| h.row == self.row_index && h.col == col)
181    }
182
183    /// 某列的批注
184    pub fn comment_at(&self, col: u16) -> Option<&Comment> {
185        self.comments
186            .iter()
187            .find(|c| c.row == self.row_index && c.col == col)
188    }
189
190    /// 某列命中的数据验证(下拉 / 数值区间)
191    pub fn validation_at(&self, col: u16) -> Option<&DataValidation> {
192        self.validations
193            .iter()
194            .find(|v| v.contains(self.row_index, col))
195    }
196
197    /// 某列命中的条件格式
198    pub fn conditional_format_at(&self, col: u16) -> Option<&ConditionalFormat> {
199        self.conditional_formats
200            .iter()
201            .find(|cf| cf.contains(self.row_index, col))
202    }
203
204    /// 某列的超链接地址(取不到返回 `None`)
205    pub fn link_of(&self, header: &str) -> Option<&str> {
206        self.link_at(self.header.index_of(header)?)?.href()
207    }
208
209    /// 某列的批注文本
210    pub fn comment_of(&self, header: &str) -> Option<&str> {
211        Some(self.comment_at(self.header.index_of(header)?)?.text.as_str())
212    }
213
214    /// 整行是否为空(含图片)
215    pub fn is_empty(&self) -> bool {
216        if !self.images.is_empty() {
217            return false;
218        }
219        self.cells.iter().all(|c| c.value.is_empty())
220    }
221
222    /// 把本行的单元格按文件列序转换为文本(错误报告 / 预览用)
223    pub fn to_text_row(&self) -> Vec<String> {
224        (0..self.header.file_headers.len() as u16)
225            .map(|col| self.cell_at(col).map(|c| c.text()).unwrap_or_default())
226            .collect()
227    }
228
229    /// 未在表头出现但模型声明过的列(用于区分"缺列"与"空值")
230    pub fn missing_columns(&self) -> Vec<String> {
231        self.header
232            .columns
233            .iter()
234            .filter(|c| !c.is_matched())
235            .map(|c| c.header.clone())
236            .collect()
237    }
238}
239
240/// 一行数据的业务模型
241///
242/// 通常用 `#[derive(ExcelRow)]` 生成实现,也可以手写以处理非常规逻辑。
243pub trait ExcelRow: Sized + Send + 'static {
244    /// 列定义(表头 / 别名 / 必填 / 类型 / 图片列)
245    fn columns() -> Vec<ColumnDef>;
246
247    /// 解析一行;返回逐列错误(非空表示该行失败)
248    fn from_row(row: &RowData<'_>) -> Result<Self, Vec<ColumnError>>;
249
250    /// 写出一行(与 [`ExcelRow::columns`] 顺序对齐)
251    fn to_row(&self) -> Vec<CellValue>;
252
253    /// 该模型默认落到哪个 sheet(多 sheet 导出时使用)
254    fn sheet_name() -> Option<&'static str> {
255        None
256    }
257
258    /// 行级业务校验(在解析成功后调用,错误会记入该行)
259    fn validate(&self) -> Result<(), Vec<String>> {
260        Ok(())
261    }
262}
263
264/// 完全动态的行:不预声明列,文件有什么列收什么列("动态导入表格头适配")
265#[derive(Debug, Clone, Default)]
266pub struct DynamicRow {
267    /// (表头, 值),按文件列序
268    pub entries: Vec<(String, CellValue)>,
269}
270
271impl DynamicRow {
272    pub fn get(&self, header: &str) -> Option<&CellValue> {
273        self.entries
274            .iter()
275            .find(|(h, _)| h == header)
276            .map(|(_, v)| v)
277    }
278
279    pub fn text(&self, header: &str) -> String {
280        self.get(header).map(|v| v.to_text()).unwrap_or_default()
281    }
282
283    pub fn len(&self) -> usize {
284        self.entries.len()
285    }
286
287    pub fn is_empty(&self) -> bool {
288        self.entries.is_empty()
289    }
290
291    pub fn headers(&self) -> Vec<String> {
292        self.entries.iter().map(|(h, _)| h.clone()).collect()
293    }
294}
295
296impl ExcelRow for DynamicRow {
297    fn columns() -> Vec<ColumnDef> {
298        // 空声明 = 动态模式(不校验必填列,所有文件列都收下)
299        Vec::new()
300    }
301
302    fn from_row(row: &RowData<'_>) -> Result<Self, Vec<ColumnError>> {
303        let entries = row
304            .header
305            .file_headers
306            .iter()
307            .enumerate()
308            .map(|(i, h)| {
309                let v = row
310                    .cell_at(i as u16)
311                    .map(|c| c.value.clone())
312                    .unwrap_or(CellValue::Empty);
313                (h.clone(), v)
314            })
315            .collect();
316        Ok(DynamicRow { entries })
317    }
318
319    fn to_row(&self) -> Vec<CellValue> {
320        self.entries.iter().map(|(_, v)| v.clone()).collect()
321    }
322}
323
324/// 便捷:把一组单元格值转成模型(写库前手工转换用)
325pub fn values_of<T: IntoCell>(items: &[T]) -> Vec<CellValue> {
326    items.iter().map(|v| v.into_cell()).collect()
327}
328
329/// 列名 → Excel 列号(错误提示里定位到具体列)
330pub fn excel_column_of(index: u16) -> String {
331    excel_column_name(index)
332}