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};
#[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 {
pub sheet_name: String,
pub title: Option<String>,
pub columns: Vec<ColumnDef>,
pub notes: Vec<String>,
pub sample_rows: Vec<Vec<CellValue>>,
pub reference_sheets: Vec<ReferenceSheet>,
pub write: WriteOptions,
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
}
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
}
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
}
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();
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);
}
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();
}
}
}
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)?;
}
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()?;
}
{
let mut ws = writer.add_sheet(&SheetOptions::new("填写说明"))?;
let notes = build_notes(spec, !sample_rows.is_empty());
for line in ¬es {
ws.write_text_row([line.clone()])?;
}
}
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
}