fast-excel 1.0.0

通用 Excel 导入导出工具:流式读写(百万级)、动态表头适配、多 sheet、单元格图片、批量落库(纯 Rust,对标 EasyExcel)
Documentation
//! 导入模板生成(表头 + 必填标红 + 示例行 + 下拉 + 说明 / 引用 sheet)
//!
//! 与导出共用同一套列定义,所以"模板 / 导出 / 导入校验"三处的表头永远一致——
//! 这是旧实现里最容易走偏的地方(模板改了、导入没改,或者反过来)。

use std::path::Path;
use std::sync::Arc;

use crate::column::ColumnDef;
use crate::error::Result;
use crate::value::CellValue;
use crate::write::{ExcelWriter, SheetOptions, WriteOptions};

/// 引用 sheet(如"可用工厂列表",供填写时对照)
#[derive(Debug, Clone, Default)]
pub struct ReferenceSheet {
    pub name: String,
    /// 表头
    pub headers: Vec<String>,
    /// 数据行
    pub rows: Vec<Vec<String>>,
    /// 表格上方的说明
    pub notes: Vec<String>,
}

impl ReferenceSheet {
    pub fn new(name: impl Into<String>, headers: Vec<String>) -> Self {
        Self {
            name: name.into(),
            headers,
            rows: Vec::new(),
            notes: Vec::new(),
        }
    }

    pub fn rows(mut self, rows: Vec<Vec<String>>) -> Self {
        self.rows = rows;
        self
    }

    pub fn note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());
        self
    }
}

/// 模板示例行表达式:拿到列定义,返回一行值
pub type SampleExpr = Arc<dyn Fn(&[ColumnDef]) -> Vec<CellValue> + Send + Sync>;
/// 模板列默认值表达式
pub type DefaultExpr = Arc<dyn Fn() -> CellValue + Send + Sync>;

/// 模板定义
#[derive(Clone)]
pub struct TemplateSpec {
    /// 数据 sheet 名(默认 `导入模板`)
    pub sheet_name: String,
    /// 可选标题行(写在表头之前;写了标题行则表头在第 2 行)
    pub title: Option<String>,
    pub columns: Vec<ColumnDef>,
    /// 填写说明(写到"填写说明" sheet)
    pub notes: Vec<String>,
    /// 示例行(写到表头下方,提交前删除或替换)
    pub sample_rows: Vec<Vec<CellValue>>,
    /// 引用 sheet
    pub reference_sheets: Vec<ReferenceSheet>,
    pub write: WriteOptions,
    /// 下拉验证生效的最大行号(默认 1000)
    pub dropdown_rows: u32,
    /// 示例行表达式(拿到列定义,返回一行值;常用于「默认今天 / 按列生成」)
    pub sample_exprs: Vec<SampleExpr>,
    /// 默认值表达式(按表头;示例行里该列为空时用表达式填充)
    pub default_exprs: Vec<(String, DefaultExpr)>,
    /// 顶层合并表头分组:`(标题, 跨列数)`,写在列名表头之上(多级表头)
    pub header_groups: Vec<(String, u16)>,
}

impl std::fmt::Debug for TemplateSpec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TemplateSpec")
            .field("sheet_name", &self.sheet_name)
            .field("title", &self.title)
            .field("columns", &self.columns)
            .field("notes", &self.notes)
            .field("sample_rows", &self.sample_rows)
            .field("reference_sheets", &self.reference_sheets)
            .field("write", &self.write)
            .field("dropdown_rows", &self.dropdown_rows)
            .field("sample_exprs", &self.sample_exprs.len())
            .field(
                "default_exprs",
                &self
                    .default_exprs
                    .iter()
                    .map(|(h, _)| h)
                    .collect::<Vec<_>>(),
            )
            .field("header_groups", &self.header_groups)
            .finish()
    }
}

impl TemplateSpec {
    pub fn new(columns: Vec<ColumnDef>) -> Self {
        Self {
            sheet_name: "导入模板".to_string(),
            title: None,
            columns,
            notes: Vec::new(),
            sample_rows: Vec::new(),
            reference_sheets: Vec::new(),
            write: WriteOptions::default().in_memory(),
            dropdown_rows: 1000,
            sample_exprs: Vec::new(),
            default_exprs: Vec::new(),
            header_groups: Vec::new(),
        }
    }

    pub fn sheet_name(mut self, name: impl Into<String>) -> Self {
        self.sheet_name = name.into();
        self
    }

    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());
        self
    }

    pub fn notes<I, S>(mut self, notes: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.notes.extend(notes.into_iter().map(Into::into));
        self
    }

    pub fn sample_row(mut self, row: Vec<CellValue>) -> Self {
        self.sample_rows.push(row);
        self
    }

    /// 用**表达式**生成示例行(拿到列定义,返回一行值)
    ///
    /// ```ignore
    /// use fast_excel::{CellValue, funcs};
    /// let spec = TemplateSpec::new(columns).sample_expr(|cols| {
    ///     cols.iter().map(|c| match c.header.as_str() {
    ///         "填表日期" => CellValue::Date(funcs::today()),
    ///         "数量" => CellValue::Number(100.0),
    ///         _ => CellValue::Empty,
    ///     }).collect()
    /// });
    /// ```
    pub fn sample_expr<F>(mut self, f: F) -> Self
    where
        F: Fn(&[ColumnDef]) -> Vec<CellValue> + Send + Sync + 'static,
    {
        self.sample_exprs.push(Arc::new(f));
        self
    }

    /// 给某列配一个**默认值表达式**(示例行里该列为空时用它填充;每次生成模板都会重新求值)
    pub fn default_expr<F>(mut self, header: impl Into<String>, f: F) -> Self
    where
        F: Fn() -> CellValue + Send + Sync + 'static,
    {
        self.default_exprs.push((header.into(), Arc::new(f)));
        self
    }

    /// 追加**顶层合并表头分组**(多级表头):`标题` 横向合并 `span` 列,写在列名表头之上
    ///
    /// 各分组按顺序从左往右排布,跨列数之和应等于列数(不足的部分留空)。
    ///
    /// ```ignore
    /// let spec = TemplateSpec::new(ProductRow::columns())
    ///     .header_group("基本信息", 3)   // A1:C1 合并
    ///     .header_group("价格信息", 2);  // D1:E1 合并
    /// ```
    pub fn header_group(mut self, title: impl Into<String>, span: u16) -> Self {
        self.header_groups.push((title.into(), span.max(1)));
        self
    }

    pub fn reference(mut self, sheet: ReferenceSheet) -> Self {
        self.reference_sheets.push(sheet);
        self
    }

    pub fn write_options(mut self, write: WriteOptions) -> Self {
        self.write = write;
        self
    }

    pub fn dropdown_rows(mut self, rows: u32) -> Self {
        self.dropdown_rows = rows;
        self
    }

    /// 表头行号(0 基):有标题行 +1;有多级合并表头再 +1
    pub fn header_row(&self) -> u32 {
        let mut row = if self.title.is_some() { 1 } else { 0 };
        if !self.header_groups.is_empty() {
            row += 1;
        }
        row
    }
}

/// 生成模板字节
pub fn build_template(spec: &TemplateSpec) -> Result<Vec<u8>> {
    let mut writer = ExcelWriter::new();
    let header_row = spec.header_row();
    let columns = spec.columns.clone();

    // 示例行:显式行 + 表达式行,再用默认值表达式 / 列 default 兜底空列
    let mut sample_rows = spec.sample_rows.clone();
    for f in &spec.sample_exprs {
        sample_rows.push(f(&columns));
    }
    let has_static_default = columns.iter().any(|c| c.default.is_some());
    if has_static_default || !spec.default_exprs.is_empty() {
        if sample_rows.is_empty() {
            sample_rows.push(vec![CellValue::Empty; columns.len()]);
        }
        for row in sample_rows.iter_mut() {
            while row.len() < columns.len() {
                row.push(CellValue::Empty);
            }
            // 1) 动态默认值表达式优先
            for (header, f) in &spec.default_exprs {
                if let Some(index) = columns.iter().position(|c| &c.header == header) {
                    if row[index].is_empty() {
                        row[index] = f();
                    }
                }
            }
            // 2) 列上的静态 default 兜底(ColumnDef::default / #[excel(default = "...")])
            for (index, col) in columns.iter().enumerate() {
                if row[index].is_empty() {
                    if let Some(value) = &col.default {
                        row[index] = CellValue::Text(value.clone());
                    }
                }
            }
        }
    }

    {
        let sheet_options = SheetOptions::new(&spec.sheet_name)
            .columns(columns.clone())
            .write_options(spec.write.clone());
        let mut ws = writer.add_sheet(&sheet_options)?;
        if let Some(title) = &spec.title {
            ws.write_text_row([title.clone()])?;
        }
        if !spec.header_groups.is_empty() {
            ws.write_merged_header_row(&spec.header_groups)?;
        }
        ws.write_headers_marked(&columns)?;
        for row in &sample_rows {
            ws.write_row(row)?;
        }
        // 下拉验证(模板场景数据量小,直接给到 dropdown_rows 行)
        let first = header_row + 1;
        let last = header_row + spec.dropdown_rows;
        for (i, col) in columns.iter().enumerate() {
            if !col.dropdown.is_empty() {
                let prompt = col.note.clone();
                ws.add_dropdown(i as u16, &col.dropdown, first, last, prompt.as_deref())?;
            }
        }
        ws.finish()?;
    }

    // 填写说明 sheet
    {
        let mut ws = writer.add_sheet(&SheetOptions::new("填写说明"))?;
        let notes = build_notes(spec, !sample_rows.is_empty());
        for line in &notes {
            ws.write_text_row([line.clone()])?;
        }
    }

    // 引用 sheet
    for reference in &spec.reference_sheets {
        let mut ws = writer.add_sheet(&SheetOptions::new(&reference.name))?;
        for line in &reference.notes {
            ws.write_text_row([line.clone()])?;
        }
        ws.write_text_row(reference.headers.clone())?;
        for row in &reference.rows {
            ws.write_text_row(row.clone())?;
        }
    }

    writer.save_to_buffer()
}

/// 生成模板文件
pub fn write_template_file<P: AsRef<Path>>(path: P, spec: &TemplateSpec) -> Result<u64> {
    let bytes = build_template(spec)?;
    std::fs::write(path.as_ref(), &bytes)?;
    Ok(bytes.len() as u64)
}

fn build_notes(spec: &TemplateSpec, has_sample: bool) -> Vec<String> {
    let mut notes = Vec::new();
    notes.push(format!("填写说明(数据 sheet:{})", spec.sheet_name));
    notes.push(String::new());

    let required: Vec<String> = spec
        .columns
        .iter()
        .filter(|c| c.required)
        .map(|c| c.header.clone())
        .collect();
    if required.is_empty() {
        notes.push("1. 表头列均为选填。".to_string());
    } else {
        notes.push(format!("1. 红色表头为必填列:{}。", required.join("、")));
    }

    let image_cols: Vec<String> = spec
        .columns
        .iter()
        .filter(|c| c.image)
        .map(|c| c.header.clone())
        .collect();
    if !image_cols.is_empty() {
        notes.push(format!(
            "2. 图片列({}):把图片直接插入/粘贴到对应单元格,导入时按行自动对应,不需要打包 zip。",
            image_cols.join("、")
        ));
    }

    let mut idx = 3;
    if has_sample {
        notes.push(format!(
            "{idx}. 第 {} 行是示例数据,正式导入前请删除或整行替换。",
            spec.header_row() + 2
        ));
        idx += 1;
    }
    for line in &spec.notes {
        notes.push(format!("{idx}. {line}"));
        idx += 1;
    }

    notes.push(String::new());
    notes.push("列说明:".to_string());
    for col in &spec.columns {
        let mut desc = vec![col.header.clone()];
        if col.required {
            desc.push("必填".to_string());
        }
        desc.push(col.kind.as_str().to_string());
        if let Some(note) = &col.note {
            desc.push(note.clone());
        }
        if !col.dropdown.is_empty() {
            desc.push(format!("可选值:{}", col.dropdown.join("/")));
        }
        notes.push(format!("- {}", desc.join(" | ")));
    }
    notes
}