Skip to main content

fast_excel/write/
template.rs

1//! 导入模板生成(表头 + 必填标红 + 示例行 + 下拉 + 说明 / 引用 sheet)
2//!
3//! 与导出共用同一套列定义,所以"模板 / 导出 / 导入校验"三处的表头永远一致——
4//! 这是旧实现里最容易走偏的地方(模板改了、导入没改,或者反过来)。
5
6use std::path::Path;
7use std::sync::Arc;
8
9use crate::column::ColumnDef;
10use crate::error::Result;
11use crate::value::CellValue;
12use crate::write::{ExcelWriter, SheetOptions, WriteOptions};
13
14/// 引用 sheet(如"可用工厂列表",供填写时对照)
15#[derive(Debug, Clone, Default)]
16pub struct ReferenceSheet {
17    pub name: String,
18    /// 表头
19    pub headers: Vec<String>,
20    /// 数据行
21    pub rows: Vec<Vec<String>>,
22    /// 表格上方的说明
23    pub notes: Vec<String>,
24}
25
26impl ReferenceSheet {
27    pub fn new(name: impl Into<String>, headers: Vec<String>) -> Self {
28        Self {
29            name: name.into(),
30            headers,
31            rows: Vec::new(),
32            notes: Vec::new(),
33        }
34    }
35
36    pub fn rows(mut self, rows: Vec<Vec<String>>) -> Self {
37        self.rows = rows;
38        self
39    }
40
41    pub fn note(mut self, note: impl Into<String>) -> Self {
42        self.notes.push(note.into());
43        self
44    }
45}
46
47/// 模板示例行表达式:拿到列定义,返回一行值
48pub type SampleExpr = Arc<dyn Fn(&[ColumnDef]) -> Vec<CellValue> + Send + Sync>;
49/// 模板列默认值表达式
50pub type DefaultExpr = Arc<dyn Fn() -> CellValue + Send + Sync>;
51
52/// 模板定义
53#[derive(Clone)]
54pub struct TemplateSpec {
55    /// 数据 sheet 名(默认 `导入模板`)
56    pub sheet_name: String,
57    /// 可选标题行(写在表头之前;写了标题行则表头在第 2 行)
58    pub title: Option<String>,
59    pub columns: Vec<ColumnDef>,
60    /// 填写说明(写到"填写说明" sheet)
61    pub notes: Vec<String>,
62    /// 示例行(写到表头下方,提交前删除或替换)
63    pub sample_rows: Vec<Vec<CellValue>>,
64    /// 引用 sheet
65    pub reference_sheets: Vec<ReferenceSheet>,
66    pub write: WriteOptions,
67    /// 下拉验证生效的最大行号(默认 1000)
68    pub dropdown_rows: u32,
69    /// 示例行表达式(拿到列定义,返回一行值;常用于「默认今天 / 按列生成」)
70    pub sample_exprs: Vec<SampleExpr>,
71    /// 默认值表达式(按表头;示例行里该列为空时用表达式填充)
72    pub default_exprs: Vec<(String, DefaultExpr)>,
73    /// 顶层合并表头分组:`(标题, 跨列数)`,写在列名表头之上(多级表头)
74    pub header_groups: Vec<(String, u16)>,
75}
76
77impl std::fmt::Debug for TemplateSpec {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.debug_struct("TemplateSpec")
80            .field("sheet_name", &self.sheet_name)
81            .field("title", &self.title)
82            .field("columns", &self.columns)
83            .field("notes", &self.notes)
84            .field("sample_rows", &self.sample_rows)
85            .field("reference_sheets", &self.reference_sheets)
86            .field("write", &self.write)
87            .field("dropdown_rows", &self.dropdown_rows)
88            .field("sample_exprs", &self.sample_exprs.len())
89            .field(
90                "default_exprs",
91                &self
92                    .default_exprs
93                    .iter()
94                    .map(|(h, _)| h)
95                    .collect::<Vec<_>>(),
96            )
97            .field("header_groups", &self.header_groups)
98            .finish()
99    }
100}
101
102impl TemplateSpec {
103    pub fn new(columns: Vec<ColumnDef>) -> Self {
104        Self {
105            sheet_name: "导入模板".to_string(),
106            title: None,
107            columns,
108            notes: Vec::new(),
109            sample_rows: Vec::new(),
110            reference_sheets: Vec::new(),
111            write: WriteOptions::default().in_memory(),
112            dropdown_rows: 1000,
113            sample_exprs: Vec::new(),
114            default_exprs: Vec::new(),
115            header_groups: Vec::new(),
116        }
117    }
118
119    pub fn sheet_name(mut self, name: impl Into<String>) -> Self {
120        self.sheet_name = name.into();
121        self
122    }
123
124    pub fn title(mut self, title: impl Into<String>) -> Self {
125        self.title = Some(title.into());
126        self
127    }
128
129    pub fn note(mut self, note: impl Into<String>) -> Self {
130        self.notes.push(note.into());
131        self
132    }
133
134    pub fn notes<I, S>(mut self, notes: I) -> Self
135    where
136        I: IntoIterator<Item = S>,
137        S: Into<String>,
138    {
139        self.notes.extend(notes.into_iter().map(Into::into));
140        self
141    }
142
143    pub fn sample_row(mut self, row: Vec<CellValue>) -> Self {
144        self.sample_rows.push(row);
145        self
146    }
147
148    /// 用**表达式**生成示例行(拿到列定义,返回一行值)
149    ///
150    /// ```ignore
151    /// use fast_excel::{CellValue, funcs};
152    /// let spec = TemplateSpec::new(columns).sample_expr(|cols| {
153    ///     cols.iter().map(|c| match c.header.as_str() {
154    ///         "填表日期" => CellValue::Date(funcs::today()),
155    ///         "数量" => CellValue::Number(100.0),
156    ///         _ => CellValue::Empty,
157    ///     }).collect()
158    /// });
159    /// ```
160    pub fn sample_expr<F>(mut self, f: F) -> Self
161    where
162        F: Fn(&[ColumnDef]) -> Vec<CellValue> + Send + Sync + 'static,
163    {
164        self.sample_exprs.push(Arc::new(f));
165        self
166    }
167
168    /// 给某列配一个**默认值表达式**(示例行里该列为空时用它填充;每次生成模板都会重新求值)
169    pub fn default_expr<F>(mut self, header: impl Into<String>, f: F) -> Self
170    where
171        F: Fn() -> CellValue + Send + Sync + 'static,
172    {
173        self.default_exprs.push((header.into(), Arc::new(f)));
174        self
175    }
176
177    /// 追加**顶层合并表头分组**(多级表头):`标题` 横向合并 `span` 列,写在列名表头之上
178    ///
179    /// 各分组按顺序从左往右排布,跨列数之和应等于列数(不足的部分留空)。
180    ///
181    /// ```ignore
182    /// let spec = TemplateSpec::new(ProductRow::columns())
183    ///     .header_group("基本信息", 3)   // A1:C1 合并
184    ///     .header_group("价格信息", 2);  // D1:E1 合并
185    /// ```
186    pub fn header_group(mut self, title: impl Into<String>, span: u16) -> Self {
187        self.header_groups.push((title.into(), span.max(1)));
188        self
189    }
190
191    pub fn reference(mut self, sheet: ReferenceSheet) -> Self {
192        self.reference_sheets.push(sheet);
193        self
194    }
195
196    pub fn write_options(mut self, write: WriteOptions) -> Self {
197        self.write = write;
198        self
199    }
200
201    pub fn dropdown_rows(mut self, rows: u32) -> Self {
202        self.dropdown_rows = rows;
203        self
204    }
205
206    /// 表头行号(0 基):有标题行 +1;有多级合并表头再 +1
207    pub fn header_row(&self) -> u32 {
208        let mut row = if self.title.is_some() { 1 } else { 0 };
209        if !self.header_groups.is_empty() {
210            row += 1;
211        }
212        row
213    }
214}
215
216/// 生成模板字节
217pub fn build_template(spec: &TemplateSpec) -> Result<Vec<u8>> {
218    let mut writer = ExcelWriter::new();
219    let header_row = spec.header_row();
220    let columns = spec.columns.clone();
221
222    // 示例行:显式行 + 表达式行,再用默认值表达式 / 列 default 兜底空列
223    let mut sample_rows = spec.sample_rows.clone();
224    for f in &spec.sample_exprs {
225        sample_rows.push(f(&columns));
226    }
227    let has_static_default = columns.iter().any(|c| c.default.is_some());
228    if has_static_default || !spec.default_exprs.is_empty() {
229        if sample_rows.is_empty() {
230            sample_rows.push(vec![CellValue::Empty; columns.len()]);
231        }
232        for row in sample_rows.iter_mut() {
233            while row.len() < columns.len() {
234                row.push(CellValue::Empty);
235            }
236            // 1) 动态默认值表达式优先
237            for (header, f) in &spec.default_exprs {
238                if let Some(index) = columns.iter().position(|c| &c.header == header) {
239                    if row[index].is_empty() {
240                        row[index] = f();
241                    }
242                }
243            }
244            // 2) 列上的静态 default 兜底(ColumnDef::default / #[excel(default = "...")])
245            for (index, col) in columns.iter().enumerate() {
246                if row[index].is_empty() {
247                    if let Some(value) = &col.default {
248                        row[index] = CellValue::Text(value.clone());
249                    }
250                }
251            }
252        }
253    }
254
255    {
256        let sheet_options = SheetOptions::new(&spec.sheet_name)
257            .columns(columns.clone())
258            .write_options(spec.write.clone());
259        let mut ws = writer.add_sheet(&sheet_options)?;
260        if let Some(title) = &spec.title {
261            ws.write_text_row([title.clone()])?;
262        }
263        if !spec.header_groups.is_empty() {
264            ws.write_merged_header_row(&spec.header_groups)?;
265        }
266        ws.write_headers_marked(&columns)?;
267        for row in &sample_rows {
268            ws.write_row(row)?;
269        }
270        // 下拉验证(模板场景数据量小,直接给到 dropdown_rows 行)
271        let first = header_row + 1;
272        let last = header_row + spec.dropdown_rows;
273        for (i, col) in columns.iter().enumerate() {
274            if !col.dropdown.is_empty() {
275                let prompt = col.note.clone();
276                ws.add_dropdown(i as u16, &col.dropdown, first, last, prompt.as_deref())?;
277            }
278        }
279        ws.finish()?;
280    }
281
282    // 填写说明 sheet
283    {
284        let mut ws = writer.add_sheet(&SheetOptions::new("填写说明"))?;
285        let notes = build_notes(spec, !sample_rows.is_empty());
286        for line in &notes {
287            ws.write_text_row([line.clone()])?;
288        }
289    }
290
291    // 引用 sheet
292    for reference in &spec.reference_sheets {
293        let mut ws = writer.add_sheet(&SheetOptions::new(&reference.name))?;
294        for line in &reference.notes {
295            ws.write_text_row([line.clone()])?;
296        }
297        ws.write_text_row(reference.headers.clone())?;
298        for row in &reference.rows {
299            ws.write_text_row(row.clone())?;
300        }
301    }
302
303    writer.save_to_buffer()
304}
305
306/// 生成模板文件
307pub fn write_template_file<P: AsRef<Path>>(path: P, spec: &TemplateSpec) -> Result<u64> {
308    let bytes = build_template(spec)?;
309    std::fs::write(path.as_ref(), &bytes)?;
310    Ok(bytes.len() as u64)
311}
312
313fn build_notes(spec: &TemplateSpec, has_sample: bool) -> Vec<String> {
314    let mut notes = Vec::new();
315    notes.push(format!("填写说明(数据 sheet:{})", spec.sheet_name));
316    notes.push(String::new());
317
318    let required: Vec<String> = spec
319        .columns
320        .iter()
321        .filter(|c| c.required)
322        .map(|c| c.header.clone())
323        .collect();
324    if required.is_empty() {
325        notes.push("1. 表头列均为选填。".to_string());
326    } else {
327        notes.push(format!("1. 红色表头为必填列:{}。", required.join("、")));
328    }
329
330    let image_cols: Vec<String> = spec
331        .columns
332        .iter()
333        .filter(|c| c.image)
334        .map(|c| c.header.clone())
335        .collect();
336    if !image_cols.is_empty() {
337        notes.push(format!(
338            "2. 图片列({}):把图片直接插入/粘贴到对应单元格,导入时按行自动对应,不需要打包 zip。",
339            image_cols.join("、")
340        ));
341    }
342
343    let mut idx = 3;
344    if has_sample {
345        notes.push(format!(
346            "{idx}. 第 {} 行是示例数据,正式导入前请删除或整行替换。",
347            spec.header_row() + 2
348        ));
349        idx += 1;
350    }
351    for line in &spec.notes {
352        notes.push(format!("{idx}. {line}"));
353        idx += 1;
354    }
355
356    notes.push(String::new());
357    notes.push("列说明:".to_string());
358    for col in &spec.columns {
359        let mut desc = vec![col.header.clone()];
360        if col.required {
361            desc.push("必填".to_string());
362        }
363        desc.push(col.kind.as_str().to_string());
364        if let Some(note) = &col.note {
365            desc.push(note.clone());
366        }
367        if !col.dropdown.is_empty() {
368            desc.push(format!("可选值:{}", col.dropdown.join("/")));
369        }
370        notes.push(format!("- {}", desc.join(" | ")));
371    }
372    notes
373}