1use serde::Serialize;
7
8use crate::column::ColumnDef;
9use crate::header::{HeaderMap, excel_column_name};
10use crate::read::merges::MergeRange;
11use crate::read::sheet_meta::{Comment, ConditionalFormat, DataValidation, Hyperlink};
12use crate::read::styles::{CellStyle, Styles};
13use crate::value::{Cell, CellImage, CellValue, FromCell, IntoCell};
14
15#[derive(Debug, Clone, PartialEq)]
17pub struct RowImage {
18 pub column: u16,
20 pub header: String,
22 pub bytes: Vec<u8>,
23 pub ext: String,
25 pub name: Option<String>,
27}
28
29impl RowImage {
30 pub fn mime(&self) -> &'static str {
31 crate::value::mime_from_ext(&self.ext)
32 }
33
34 pub fn image(&self) -> CellImage {
35 CellImage {
36 bytes: self.bytes.clone(),
37 ext: self.ext.clone(),
38 name: self.name.clone(),
39 }
40 }
41
42 pub fn len(&self) -> usize {
44 self.bytes.len()
45 }
46
47 pub fn is_empty(&self) -> bool {
48 self.bytes.is_empty()
49 }
50}
51
52#[derive(Debug, Clone, Serialize)]
54#[serde(rename_all = "camelCase")]
55pub struct ColumnError {
56 pub column: String,
58 pub file_header: String,
60 pub message: String,
61}
62
63impl ColumnError {
64 pub fn new(column: impl Into<String>, message: impl Into<String>) -> Self {
65 Self {
66 column: column.into(),
67 file_header: String::new(),
68 message: message.into(),
69 }
70 }
71}
72
73pub struct RowData<'a> {
75 pub row_index: u32,
77 pub sheet: &'a str,
79 pub header: &'a HeaderMap,
81 pub cells: &'a [Cell],
83 pub images: &'a [RowImage],
85 pub merges: &'a [MergeRange],
87 pub styles: &'a Styles,
89 pub hyperlinks: &'a [Hyperlink],
91 pub comments: &'a [Comment],
93 pub validations: &'a [DataValidation],
95 pub conditional_formats: &'a [ConditionalFormat],
97}
98
99impl<'a> RowData<'a> {
100 pub fn cell_at(&self, col: u16) -> Option<&Cell> {
102 self.cells.iter().find(|c| c.col == col)
103 }
104
105 pub fn cell_of(&self, header: &str) -> Option<&Cell> {
107 let col = self.header.index_of(header)?;
108 self.cell_at(col)
109 }
110
111 pub fn value_of(&self, header: &str) -> Option<&CellValue> {
112 self.cell_of(header).map(|c| &c.value)
113 }
114
115 pub fn text_of(&self, header: &str) -> String {
116 self.cell_of(header).map(|c| c.text()).unwrap_or_default()
117 }
118
119 pub fn get<T: FromCell>(&self, header: &str) -> Result<T, String> {
121 match self.cell_of(header) {
122 Some(c) => T::from_cell(c),
123 None => Err(format!("缺少列「{}」", header)),
124 }
125 }
126
127 pub fn opt<T: FromCell>(&self, header: &str) -> Result<Option<T>, String> {
129 match self.cell_of(header) {
130 Some(c) if !c.value.is_empty() => T::from_cell(c).map(Some),
131 _ => Ok(None),
132 }
133 }
134
135 pub fn string(&self, header: &str) -> Option<String> {
137 let cell = self.cell_of(header)?;
138 if cell.value.is_empty() {
139 None
140 } else {
141 Some(cell.text())
142 }
143 }
144
145 pub fn images_of(&self, header: &str) -> Vec<&RowImage> {
147 let Some(col) = self.header.index_of(header) else {
148 return Vec::new();
149 };
150 self.images.iter().filter(|i| i.column == col).collect()
151 }
152
153 pub fn image_at(&self, n: usize) -> Option<&RowImage> {
155 self.images.get(n)
156 }
157
158 pub fn merged_at(&self, col: u16) -> Option<&MergeRange> {
160 self.merges
161 .iter()
162 .find(|m| col >= m.first_col && col <= m.last_col)
163 }
164
165 pub fn cell_style(&self, header: &str) -> Option<CellStyle> {
167 let col = self.header.index_of(header)?;
168 self.style_at(col)
169 }
170
171 pub fn style_at(&self, col: u16) -> Option<CellStyle> {
173 self.cell_at(col).map(|c| self.styles.cell_style(c.style))
174 }
175
176 pub fn link_at(&self, col: u16) -> Option<&Hyperlink> {
178 self.hyperlinks
179 .iter()
180 .find(|h| h.row == self.row_index && h.col == col)
181 }
182
183 pub fn comment_at(&self, col: u16) -> Option<&Comment> {
185 self.comments
186 .iter()
187 .find(|c| c.row == self.row_index && c.col == col)
188 }
189
190 pub fn validation_at(&self, col: u16) -> Option<&DataValidation> {
192 self.validations
193 .iter()
194 .find(|v| v.contains(self.row_index, col))
195 }
196
197 pub fn conditional_format_at(&self, col: u16) -> Option<&ConditionalFormat> {
199 self.conditional_formats
200 .iter()
201 .find(|cf| cf.contains(self.row_index, col))
202 }
203
204 pub fn link_of(&self, header: &str) -> Option<&str> {
206 self.link_at(self.header.index_of(header)?)?.href()
207 }
208
209 pub fn comment_of(&self, header: &str) -> Option<&str> {
211 Some(self.comment_at(self.header.index_of(header)?)?.text.as_str())
212 }
213
214 pub fn is_empty(&self) -> bool {
216 if !self.images.is_empty() {
217 return false;
218 }
219 self.cells.iter().all(|c| c.value.is_empty())
220 }
221
222 pub fn to_text_row(&self) -> Vec<String> {
224 (0..self.header.file_headers.len() as u16)
225 .map(|col| self.cell_at(col).map(|c| c.text()).unwrap_or_default())
226 .collect()
227 }
228
229 pub fn missing_columns(&self) -> Vec<String> {
231 self.header
232 .columns
233 .iter()
234 .filter(|c| !c.is_matched())
235 .map(|c| c.header.clone())
236 .collect()
237 }
238}
239
240pub trait ExcelRow: Sized + Send + 'static {
244 fn columns() -> Vec<ColumnDef>;
246
247 fn from_row(row: &RowData<'_>) -> Result<Self, Vec<ColumnError>>;
249
250 fn to_row(&self) -> Vec<CellValue>;
252
253 fn sheet_name() -> Option<&'static str> {
255 None
256 }
257
258 fn validate(&self) -> Result<(), Vec<String>> {
260 Ok(())
261 }
262}
263
264#[derive(Debug, Clone, Default)]
266pub struct DynamicRow {
267 pub entries: Vec<(String, CellValue)>,
269}
270
271impl DynamicRow {
272 pub fn get(&self, header: &str) -> Option<&CellValue> {
273 self.entries
274 .iter()
275 .find(|(h, _)| h == header)
276 .map(|(_, v)| v)
277 }
278
279 pub fn text(&self, header: &str) -> String {
280 self.get(header).map(|v| v.to_text()).unwrap_or_default()
281 }
282
283 pub fn len(&self) -> usize {
284 self.entries.len()
285 }
286
287 pub fn is_empty(&self) -> bool {
288 self.entries.is_empty()
289 }
290
291 pub fn headers(&self) -> Vec<String> {
292 self.entries.iter().map(|(h, _)| h.clone()).collect()
293 }
294}
295
296impl ExcelRow for DynamicRow {
297 fn columns() -> Vec<ColumnDef> {
298 Vec::new()
300 }
301
302 fn from_row(row: &RowData<'_>) -> Result<Self, Vec<ColumnError>> {
303 let entries = row
304 .header
305 .file_headers
306 .iter()
307 .enumerate()
308 .map(|(i, h)| {
309 let v = row
310 .cell_at(i as u16)
311 .map(|c| c.value.clone())
312 .unwrap_or(CellValue::Empty);
313 (h.clone(), v)
314 })
315 .collect();
316 Ok(DynamicRow { entries })
317 }
318
319 fn to_row(&self) -> Vec<CellValue> {
320 self.entries.iter().map(|(_, v)| v.clone()).collect()
321 }
322}
323
324pub fn values_of<T: IntoCell>(items: &[T]) -> Vec<CellValue> {
326 items.iter().map(|v| v.into_cell()).collect()
327}
328
329pub fn excel_column_of(index: u16) -> String {
331 excel_column_name(index)
332}