1use 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#[derive(Debug, Clone, Default)]
16pub struct ReferenceSheet {
17 pub name: String,
18 pub headers: Vec<String>,
20 pub rows: Vec<Vec<String>>,
22 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
47pub type SampleExpr = Arc<dyn Fn(&[ColumnDef]) -> Vec<CellValue> + Send + Sync>;
49pub type DefaultExpr = Arc<dyn Fn() -> CellValue + Send + Sync>;
51
52#[derive(Clone)]
54pub struct TemplateSpec {
55 pub sheet_name: String,
57 pub title: Option<String>,
59 pub columns: Vec<ColumnDef>,
60 pub notes: Vec<String>,
62 pub sample_rows: Vec<Vec<CellValue>>,
64 pub reference_sheets: Vec<ReferenceSheet>,
66 pub write: WriteOptions,
67 pub dropdown_rows: u32,
69 pub sample_exprs: Vec<SampleExpr>,
71 pub default_exprs: Vec<(String, DefaultExpr)>,
73 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 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 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 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 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
216pub 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 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 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 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 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 {
284 let mut ws = writer.add_sheet(&SheetOptions::new("填写说明"))?;
285 let notes = build_notes(spec, !sample_rows.is_empty());
286 for line in ¬es {
287 ws.write_text_row([line.clone()])?;
288 }
289 }
290
291 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
306pub 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}