Skip to main content

fast_excel/write/
mod.rs

1//! 写侧:流式导出(多 sheet / 单元格图片 / 模板生成)
2
3pub mod csv;
4pub mod dynamic;
5pub mod template;
6pub mod writer;
7
8pub use csv::write_csv;
9pub use dynamic::{
10    DynamicExportRunner, DynamicSheet, align_row, named_xlsx_bytes, positional_xlsx_bytes,
11    write_named_xlsx, write_positional_xlsx,
12};
13pub use template::{DefaultExpr, ReferenceSheet, SampleExpr, TemplateSpec, build_template};
14pub use writer::{ExcelWriter, SheetWriter};
15
16use std::sync::Arc;
17
18use crate::column::ColumnDef;
19use crate::expr::{CellExpr, RowValues};
20use crate::value::CellValue;
21
22/// 写出选项
23#[derive(Debug, Clone)]
24pub struct WriteOptions {
25    /// 表头样式(加粗 + 底色 + 居中)
26    pub header_style: bool,
27    /// 冻结表头行
28    pub freeze_header: bool,
29    /// 自动筛选
30    pub auto_filter: bool,
31    /// 默认行高
32    pub default_row_height: Option<f64>,
33    /// 含图片的行高(图片嵌入后按行高缩放)
34    pub image_row_height: f64,
35    /// 日期默认格式
36    pub date_format: String,
37    /// 日期时间默认格式
38    pub datetime_format: String,
39    /// 常量内存模式(**百万行必须开启**;开启后只能按行号递增写入)
40    pub constant_memory: bool,
41    /// 是否写 Excel「置于单元格内」图片(`embed_image`)
42    ///
43    /// 默认写标准锚点图片(`insert_image`):常量内存模式下可用、且能被
44    /// 本工具的读取端(drawing 锚点)与 Excel / WPS 正常识别。
45    /// 注意:`embed_image` 在 `rust_xlsxwriter` 常量内存模式下会报错,
46    /// 且生成的是 `xl/richData/*`(Excel 内嵌图片);请用 [`WriteOptions::cell_image`]
47    /// 开启——它会自动关闭常量内存;直接改字段的话请配合 `constant_memory = false`。
48    pub cell_image: bool,
49}
50
51impl Default for WriteOptions {
52    fn default() -> Self {
53        Self {
54            header_style: true,
55            freeze_header: true,
56            auto_filter: true,
57            default_row_height: None,
58            image_row_height: 60.0,
59            date_format: "yyyy-mm-dd".to_string(),
60            datetime_format: "yyyy-mm-dd hh:mm:ss".to_string(),
61            constant_memory: true,
62            cell_image: false,
63        }
64    }
65}
66
67impl WriteOptions {
68    pub fn new() -> Self {
69        Self::default()
70    }
71
72    /// 小数据量 / 需要随机写(合并单元格、绝对定位图片)时关闭常量内存
73    pub fn in_memory(mut self) -> Self {
74        self.constant_memory = false;
75        self
76    }
77
78    /// 写 Excel 内嵌单元格图片(`embed_image`)
79    ///
80    /// 内嵌图片在 `rust_xlsxwriter` 常量内存模式下支持不完整(会直接报错),
81    /// 因此这里**自动关闭常量内存**(等价于 `in_memory()`),只需调用本方法即可。
82    pub fn cell_image(mut self) -> Self {
83        self.cell_image = true;
84        self.constant_memory = false;
85        self
86    }
87
88    pub fn without_header_style(mut self) -> Self {
89        self.header_style = false;
90        self
91    }
92
93    pub fn auto_filter(mut self, enable: bool) -> Self {
94        self.auto_filter = enable;
95        self
96    }
97
98    pub fn freeze_header(mut self, enable: bool) -> Self {
99        self.freeze_header = enable;
100        self
101    }
102
103    pub fn image_row_height(mut self, height: f64) -> Self {
104        self.image_row_height = height;
105        self
106    }
107
108    pub fn date_format(mut self, format: impl Into<String>) -> Self {
109        self.date_format = format.into();
110        self
111    }
112
113    pub fn datetime_format(mut self, format: impl Into<String>) -> Self {
114        self.datetime_format = format.into();
115        self
116    }
117}
118
119/// 单个工作表的配置
120#[derive(Clone)]
121pub struct SheetOptions {
122    pub name: String,
123    /// 列定义(表头、别名、宽度、格式、图片列)
124    pub columns: Vec<ColumnDef>,
125    pub write: WriteOptions,
126    /// 计算列:导出时按表达式追加到末尾
127    pub computed: Vec<(ColumnDef, CellExpr)>,
128    /// 列改写:按表头匹配,导出时用表达式替换该列的值
129    pub transforms: Vec<(String, CellExpr)>,
130}
131
132impl std::fmt::Debug for SheetOptions {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        f.debug_struct("SheetOptions")
135            .field("name", &self.name)
136            .field("columns", &self.columns)
137            .field("write", &self.write)
138            .field(
139                "computed",
140                &self.computed.iter().map(|(d, _)| &d.header).collect::<Vec<_>>(),
141            )
142            .field(
143                "transforms",
144                &self.transforms.iter().map(|(h, _)| h).collect::<Vec<_>>(),
145            )
146            .finish()
147    }
148}
149
150impl SheetOptions {
151    pub fn new(name: impl Into<String>) -> Self {
152        Self {
153            name: name.into(),
154            columns: Vec::new(),
155            write: WriteOptions::default(),
156            computed: Vec::new(),
157            transforms: Vec::new(),
158        }
159    }
160
161    pub fn columns<I>(mut self, columns: I) -> Self
162    where
163        I: IntoIterator<Item = ColumnDef>,
164    {
165        self.columns = columns.into_iter().collect();
166        self
167    }
168
169    pub fn write_options(mut self, write: WriteOptions) -> Self {
170        self.write = write;
171        self
172    }
173
174    /// 追加一个**计算列**(导出时按表达式算出,无需模型里有对应字段)
175    ///
176    /// ```ignore
177    /// use fast_excel::{CellValue, ColumnDef, SheetOptions, funcs};
178    /// let sheet = SheetOptions::new("明细")
179    ///     .columns(ProductRow::columns())
180    ///     .computed(ColumnDef::new("全名"), |row| {
181    ///         CellValue::Text(funcs::concat(&[&row.text("姓"), &row.text("名")]))
182    ///     });
183    /// ```
184    pub fn computed<F>(mut self, def: ColumnDef, expr: F) -> Self
185    where
186        F: for<'a> Fn(&RowValues<'a>) -> CellValue + Send + Sync + 'static,
187    {
188        self.computed.push((def, Arc::new(expr)));
189        self
190    }
191
192    /// **改写已有列**的值(按表头匹配;表达式拿到的是本行其它列的原始值)
193    pub fn transform<F>(mut self, header: impl Into<String>, expr: F) -> Self
194    where
195        F: for<'a> Fn(&RowValues<'a>) -> CellValue + Send + Sync + 'static,
196    {
197        self.transforms.push((header.into(), Arc::new(expr)));
198        self
199    }
200
201    /// 实际写出的列 = 基础列 + 追加的计算列
202    pub fn effective_columns(&self) -> Vec<ColumnDef> {
203        let mut cols = self.columns.clone();
204        cols.extend(self.computed.iter().map(|(def, _)| def.clone()));
205        cols
206    }
207
208    /// 应用列表达式:先按表头改写,再追加计算列
209    pub fn eval_row(&self, mut cells: Vec<CellValue>) -> Vec<CellValue> {
210        let base = &self.columns;
211        for (header, expr) in &self.transforms {
212            let Some(index) = base.iter().position(|c| &c.header == header) else {
213                continue;
214            };
215            let value = expr(&RowValues::new(&cells, base));
216            if index < cells.len() {
217                cells[index] = value;
218            } else {
219                while cells.len() < index {
220                    cells.push(CellValue::Empty);
221                }
222                cells.push(value);
223            }
224        }
225        if !self.computed.is_empty() {
226            let all = self.effective_columns();
227            for (_, expr) in &self.computed {
228                let value = expr(&RowValues::new(&cells, &all));
229                cells.push(value);
230            }
231        }
232        cells
233    }
234}
235
236impl Default for SheetOptions {
237    fn default() -> Self {
238        Self::new("Sheet1")
239    }
240}
241
242/// 列默认宽度(按语义类型 + 表头长度估算)
243pub(crate) fn default_column_width(col: &ColumnDef) -> f64 {
244    let base: f64 = match col.kind {
245        crate::column::ColumnKind::DateTime => 20.0,
246        crate::column::ColumnKind::Date => 13.0,
247        crate::column::ColumnKind::Image => 16.0,
248        crate::column::ColumnKind::Text => 16.0,
249        _ => 12.0,
250    };
251    let header_width = col.header.chars().count() as f64 + 3.0;
252    base.max(header_width)
253}