1use std::io::Cursor;
11use std::path::Path;
12
13use calamine::{Data, Reader};
14
15use crate::detect::{Format, Sniff};
16use crate::error::{Error, Result};
17use crate::extract::container::Container;
18use crate::extract::{ExtractOpts, Extractor};
19use crate::model::{Block, Document, Inline, Row};
20
21pub struct SpreadsheetExtractor;
22
23impl Extractor for SpreadsheetExtractor {
24 fn name(&self) -> &'static str {
25 "spreadsheet"
26 }
27
28 fn supports(&self, _path: &Path, sniff: &Sniff) -> bool {
29 matches!(
30 crate::detect::detect(sniff),
31 Some(Format::Xlsx | Format::Ods)
32 )
33 }
34
35 fn extract(&self, path: &Path, _opts: &ExtractOpts) -> Result<Document> {
36 let bytes = std::fs::read(path).map_err(|e| Error::io(path, e))?;
37 let blocks = parse(&bytes).map_err(|message| Error::parse(path, message))?;
38
39 let format = crate::detect::detect_path(path).ok();
40 let mut meta = match format {
41 Some(Format::Ods) => Container::from_bytes(&bytes)
43 .ok()
44 .and_then(|mut container| container.read_optional("meta.xml"))
45 .map(|source| crate::extract::odf::metadata(Some(&source)))
46 .unwrap_or_default(),
47 _ => Container::from_bytes(&bytes)
48 .map(|mut container| crate::extract::ooxml::core_properties(&mut container))
49 .unwrap_or_default(),
50 };
51 meta.source_format = format;
52 meta.source_path = Some(path.display().to_string());
53
54 Ok(Document { meta, blocks })
55 }
56}
57
58pub fn parse(bytes: &[u8]) -> std::result::Result<Vec<Block>, String> {
60 let mut workbook = calamine::open_workbook_auto_from_rs(Cursor::new(bytes.to_vec()))
61 .map_err(|e| e.to_string())?;
62
63 let mut blocks = Vec::new();
64 for name in workbook.sheet_names() {
65 let Ok(range) = workbook.worksheet_range(&name) else {
66 continue;
67 };
68
69 let rows = used_rows(&range);
70 if rows.is_empty() {
71 continue;
72 }
73
74 blocks.push(Block::Heading {
75 level: 2,
76 text: Inline::text(name.clone()),
77 });
78
79 let mut rows = rows.into_iter().map(Row::from_texts).collect::<Vec<_>>();
80 let header = rows.remove(0);
82 blocks.push(Block::Table {
83 header: Some(header),
84 rows,
85 });
86 }
87
88 Ok(blocks)
89}
90
91fn used_rows(range: &calamine::Range<Data>) -> Vec<Vec<String>> {
93 let mut last_row = None;
94 let mut last_column = 0usize;
95
96 for (index, row) in range.rows().enumerate() {
97 if let Some(column) = row.iter().rposition(|cell| !matches!(cell, Data::Empty)) {
98 last_row = Some(index);
99 last_column = last_column.max(column);
100 }
101 }
102
103 let Some(last_row) = last_row else {
104 return Vec::new();
105 };
106
107 range
108 .rows()
109 .take(last_row + 1)
110 .map(|row| {
111 (0..=last_column)
112 .map(|column| row.get(column).map(cell_text).unwrap_or_default())
113 .collect()
114 })
115 .collect()
116}
117
118fn cell_text(cell: &Data) -> String {
120 match cell {
121 Data::Empty => String::new(),
122 Data::String(text) => text.trim().to_string(),
123 Data::Int(value) => value.to_string(),
124 Data::Float(value) => number(*value),
125 Data::Bool(value) => if *value { "TRUE" } else { "FALSE" }.to_string(),
126 Data::DateTime(value) => {
127 if value.is_duration() {
128 duration(value.as_f64())
129 } else {
130 excel_date(value.as_f64())
131 }
132 }
133 Data::DateTimeIso(text) | Data::DurationIso(text) => text.clone(),
134 Data::Error(error) => format!("#{error:?}"),
135 }
136}
137
138fn number(value: f64) -> String {
140 if value.fract() == 0.0 && value.abs() < 1e15 {
141 return format!("{}", value as i64);
142 }
143 let mut text = format!("{value}");
144 if text.contains('e') {
145 text = format!("{value:.6}");
146 while text.ends_with('0') {
147 text.pop();
148 }
149 if text.ends_with('.') {
150 text.pop();
151 }
152 }
153 text
154}
155
156fn excel_date(serial: f64) -> String {
162 let days = serial.trunc() as i64;
163 let fraction = serial - serial.trunc();
164
165 if days == 0 {
167 return time_of_day(fraction);
168 }
169
170 let epoch_offset = if days < 60 { 25_568 } else { 25_569 };
171 let (year, month, day) = civil_from_days(days - epoch_offset);
172 let date = format!("{year:04}-{month:02}-{day:02}");
173 if fraction.abs() < 1e-9 {
174 date
175 } else {
176 format!("{date} {}", time_of_day(fraction))
177 }
178}
179
180fn time_of_day(fraction: f64) -> String {
181 let total = (fraction * 86_400.0).round() as i64;
182 let (hours, minutes, seconds) = (total / 3600, (total % 3600) / 60, total % 60);
183 format!("{hours:02}:{minutes:02}:{seconds:02}")
184}
185
186fn duration(days: f64) -> String {
188 let total = (days * 86_400.0).round() as i64;
189 let (hours, minutes, seconds) = (total / 3600, (total % 3600) / 60, total % 60);
190 format!("{hours}:{minutes:02}:{seconds:02}")
191}
192
193fn civil_from_days(days: i64) -> (i64, u32, u32) {
195 let z = days + 719_468;
196 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
197 let day_of_era = z - era * 146_097;
198 let year_of_era =
199 (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
200 let year = year_of_era + era * 400;
201 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
202 let shifted_month = (5 * day_of_year + 2) / 153;
203 let day = (day_of_year - (153 * shifted_month + 2) / 5 + 1) as u32;
204 let month = if shifted_month < 10 {
205 shifted_month + 3
206 } else {
207 shifted_month - 9
208 } as u32;
209
210 (if month <= 2 { year + 1 } else { year }, month, day)
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216
217 fn xlsx(sheets: &[(&str, &[&[&str]])]) -> Vec<u8> {
219 let mut entries: Vec<(String, String)> = Vec::new();
220
221 let mut sheet_tags = String::new();
222 let mut overrides = String::new();
223 let mut rels = String::new();
224
225 for (index, (name, rows)) in sheets.iter().enumerate() {
226 let number = index + 1;
227 sheet_tags.push_str(&format!(
228 r#"<sheet name="{name}" sheetId="{number}" r:id="rId{number}"/>"#
229 ));
230 rels.push_str(&format!(
231 r#"<Relationship Id="rId{number}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet{number}.xml"/>"#
232 ));
233 overrides.push_str(&format!(
234 r#"<Override PartName="/xl/worksheets/sheet{number}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>"#
235 ));
236
237 let mut body = String::new();
238 for (row_index, row) in rows.iter().enumerate() {
239 let row_number = row_index + 1;
240 let mut cells = String::new();
241 for (column, value) in row.iter().enumerate() {
242 let reference = format!("{}{row_number}", column_name(column));
243 cells.push_str(&format!(
244 r#"<c r="{reference}" t="inlineStr"><is><t>{value}</t></is></c>"#
245 ));
246 }
247 body.push_str(&format!(r#"<row r="{row_number}">{cells}</row>"#));
248 }
249 entries.push((
250 format!("xl/worksheets/sheet{number}.xml"),
251 format!(
252 r#"<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>{body}</sheetData></worksheet>"#
253 ),
254 ));
255 }
256
257 entries.push((
258 "[Content_Types].xml".into(),
259 format!(
260 r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
261 <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
262 <Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
263 {overrides}
264 </Types>"#
265 ),
266 ));
267 entries.push((
268 "_rels/.rels".into(),
269 r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdWb" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>"#.into(),
270 ));
271 entries.push((
272 "xl/workbook.xml".into(),
273 format!(
274 r#"<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>{sheet_tags}</sheets></workbook>"#
275 ),
276 ));
277 entries.push((
278 "xl/_rels/workbook.xml.rels".into(),
279 format!(
280 r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{rels}</Relationships>"#
281 ),
282 ));
283
284 let borrowed: Vec<(&str, &str)> = entries
285 .iter()
286 .map(|(name, content)| (name.as_str(), content.as_str()))
287 .collect();
288 crate::extract::container::tests::zip_bytes(&borrowed)
289 }
290
291 fn column_name(index: usize) -> String {
292 let mut index = index;
293 let mut name = String::new();
294 loop {
295 name.insert(0, (b'A' + (index % 26) as u8) as char);
296 if index < 26 {
297 break;
298 }
299 index = index / 26 - 1;
300 }
301 name
302 }
303
304 #[test]
305 fn every_sheet_becomes_a_heading_and_a_table() {
306 let bytes = xlsx(&[
307 ("Summary", &[&["part", "qty"], &["bolt", "4"]]),
308 ("Notes", &[&["note"], &["ok"]]),
309 ]);
310
311 assert_eq!(
312 parse(&bytes).unwrap(),
313 vec![
314 Block::Heading {
315 level: 2,
316 text: Inline::text("Summary")
317 },
318 Block::Table {
319 header: Some(Row::from_texts(["part", "qty"])),
320 rows: vec![Row::from_texts(["bolt", "4"])],
321 },
322 Block::Heading {
323 level: 2,
324 text: Inline::text("Notes")
325 },
326 Block::Table {
327 header: Some(Row::from_texts(["note"])),
328 rows: vec![Row::from_texts(["ok"])],
329 },
330 ]
331 );
332 }
333
334 #[test]
335 fn an_empty_sheet_is_skipped() {
336 let bytes = xlsx(&[("Empty", &[]), ("Data", &[&["a"], &["1"]])]);
337 let blocks = parse(&bytes).unwrap();
338 assert_eq!(
339 blocks.first(),
340 Some(&Block::Heading {
341 level: 2,
342 text: Inline::text("Data")
343 })
344 );
345 assert_eq!(blocks.len(), 2);
346 }
347
348 #[test]
349 fn a_non_workbook_is_an_error() {
350 assert!(parse(b"not a spreadsheet").is_err());
351 }
352
353 #[test]
354 fn cells_render_like_a_spreadsheet_shows_them() {
355 assert_eq!(cell_text(&Data::Empty), "");
356 assert_eq!(cell_text(&Data::Int(42)), "42");
357 assert_eq!(cell_text(&Data::Float(4.5)), "4.5");
358 assert_eq!(cell_text(&Data::Float(4.0)), "4");
359 assert_eq!(cell_text(&Data::Bool(true)), "TRUE");
360 assert_eq!(cell_text(&Data::String(" padded ".into())), "padded");
361 }
362
363 #[test]
364 fn excel_serials_become_iso_dates() {
365 assert_eq!(excel_date(1.0), "1900-01-01");
368 assert_eq!(excel_date(59.0), "1900-02-28");
369 assert_eq!(excel_date(61.0), "1900-03-01");
370 assert_eq!(excel_date(25_569.0), "1970-01-01");
371 assert_eq!(excel_date(45_123.0), "2023-07-16");
372 assert_eq!(excel_date(45_123.5), "2023-07-16 12:00:00");
373 assert_eq!(excel_date(0.25), "06:00:00");
374 }
375
376 #[test]
377 fn durations_are_hours_minutes_seconds() {
378 assert_eq!(duration(1.5), "36:00:00");
379 assert_eq!(duration(0.5 / 24.0), "0:30:00");
380 }
381}