forge
Explore
Log in

Don't you dare go Hollow

iz_old

Clone
★ 0

0 watching0 forksRustGPL-3.02.2 MiB4c154b4Tahinli2 months ago301 commits

sheet.rs349 lines, 13.6 KiBHistoryRawDownload
1//! Reading an uploaded spreadsheet into the rows the file viewer lays out.
2//!
3//! No browser renders a workbook, so unlike every other [`crate::files::
4//! ViewerKind`] this one is not a src on an element: the bytes are parsed
5//! here and come out as strings the view puts in a `<table>`. Values only —
6//! a cell's formula, formatting, charts and images are not carried over.
7//!
8//! A sheet is read one window at a time, never whole: a page of rows and a
9//! page of columns, both moved by links. A book of any size costs the same
10//! page, and nothing has to be dragged sideways to reach a column.
11
12use std::io::Cursor;
13
14use calamine::{Data, Reader, Xlsx, open_workbook_auto_from_rs, open_workbook_from_rs};
15
16/// One window of a sheet. Sized to land on a screen rather than to be
17/// generous: what does not fit is one link away, and a page that has to be
18/// panned is the thing paging exists to avoid.
19pub(crate) const ROWS_PER_PAGE: usize = 50;
20pub(crate) const COLUMNS_PER_PAGE: usize = 12;
21
22/// One window of one sheet, ready to lay out: every sheet's name for the tab
23/// strip, which of them this is, where the window sits, and whether the sheet
24/// runs past it.
25pub(crate) struct Sheet {
26 pub names: Vec<String>,
27 pub index: usize,
28 pub rows: Vec<Vec<String>>,
29 /// Zero-based offsets of the window's own corner, for the row numbers and
30 /// column letters the grid draws down its edges.
31 pub first_row: usize,
32 pub first_column: usize,
33 /// The whole sheet's size, when the file says so and the reading agrees.
34 /// An xlsx declares its own dimensions and plenty of writers get them
35 /// wrong, so a count that cannot be trusted is no count at all rather
36 /// than a number the footer would print as fact.
37 pub total_rows: Option<usize>,
38 pub total_columns: Option<usize>,
39 /// Whether there is another window past this one. Observed, not derived
40 /// from the count: a cell arriving past the window is proof, and proof is
41 /// what a pager needs.
42 pub more_rows: bool,
43 pub more_columns: bool,
44}
45
46impl Sheet {
47 /// The window's own last row and column, one-based — what the footer
48 /// counts up to.
49 pub fn last_row(&self) -> usize {
50 self.first_row + self.rows.len()
51 }
52
53 pub fn last_column(&self) -> usize {
54 self.first_column + self.rows.iter().map(Vec::len).max().unwrap_or(0)
55 }
56}
57
58/// The `index`-th sheet of the workbook, windowed to `row_page` and
59/// `column_page`. `None` when the bytes are not a workbook any reader here
60/// understands — a `.doc` that sniffed as an OLE container, or an `.xlsx`
61/// truncated in transit. An out-of-range sheet or page (a hand-edited query
62/// string) falls back to the first one rather than failing.
63pub(crate) fn read(
64 bytes: Vec<u8>,
65 index: usize,
66 row_page: usize,
67 column_page: usize,
68) -> Option<Sheet> {
69 // xlsx first, because that is the format that holds millions of rows and
70 // the only one calamine will hand over a cell at a time. Reading the
71 // whole range of a 300,000-row book costs about 380MB and most of a
72 // second; stopping at the end of the window costs neither.
73 read_streamed(&bytes, index, row_page, column_page)
74 .or_else(|| read_whole(bytes, index, row_page, column_page))
75}
76
77/// The lazy path: an xlsx read cell by cell in stream order, abandoned the
78/// moment the rows past the window start. `None` when the bytes are not an
79/// xlsx at all, which is the caller's cue to try the other formats.
80fn read_streamed(
81 bytes: &[u8],
82 index: usize,
83 row_page: usize,
84 column_page: usize,
85) -> Option<Sheet> {
86 let mut book: Xlsx<Cursor<Vec<u8>>> = open_workbook_from_rs(Cursor::new(bytes.to_vec())).ok()?;
87 let names = book.sheet_names();
88 if names.is_empty() {
89 return None;
90 }
91 let index = if index < names.len() { index } else { 0 };
92 let mut cells = book.worksheet_cells_reader(&names[index]).ok()?;
93 let bounds = cells.dimensions();
94 let (sheet_row, sheet_column) = bounds.start;
95 let declared_rows = bounds.end.0.saturating_sub(sheet_row) as usize + 1;
96 let declared_columns = bounds.end.1.saturating_sub(sheet_column) as usize + 1;
97 // The asked-for page is honoured whatever the file declares: an xlsx
98 // dimension is a claim, not a fact, and clamping to a wrong one would
99 // snap a reader back to the first window every time they stepped on.
100 let (first_row, first_column) = (row_page * ROWS_PER_PAGE, column_page * COLUMNS_PER_PAGE);
101 let mut rows: Vec<Vec<String>> = Vec::new();
102 let mut more_rows = false;
103 let mut more_columns = false;
104 let mut seen_rows = 0;
105 let mut seen_columns = 0;
106 while let Ok(Some(found)) = cells.next_cell() {
107 let (row, column) = found.get_position();
108 // A cell before the sheet's own first row or column is a dimension
109 // that lied; there is nowhere to put it, so it is passed over.
110 let (Some(row), Some(column)) = (
111 row.checked_sub(sheet_row).map(|row| row as usize),
112 column.checked_sub(sheet_column).map(|column| column as usize),
113 ) else {
114 continue;
115 };
116 seen_rows = seen_rows.max(row + 1);
117 seen_columns = seen_columns.max(column + 1);
118 // Cells arrive in row order, so the first one past the window is both
119 // the end of the reading and the proof there is another window.
120 if row >= first_row + ROWS_PER_PAGE {
121 more_rows = true;
122 break;
123 }
124 if column >= first_column + COLUMNS_PER_PAGE {
125 more_columns = true;
126 continue;
127 }
128 if row < first_row || column < first_column {
129 continue;
130 }
131 let (row, column) = (row - first_row, column - first_column);
132 if rows.len() <= row {
133 rows.resize(row + 1, Vec::new());
134 }
135 let line = &mut rows[row];
136 if line.len() <= column {
137 line.resize(column + 1, String::new());
138 }
139 line[column] = cell(&Data::from(found.get_value().clone()));
140 }
141 // The declared size is believed only where the reading bears it out. A
142 // sheet whose cells ran past what it declared has a wrong dimension, and
143 // one abandoned mid-read was never counted at all.
144 let counted = !more_rows;
145 Some(Sheet {
146 names,
147 index,
148 total_rows: (counted && declared_rows >= seen_rows).then_some(declared_rows.max(seen_rows)),
149 total_columns: (declared_columns >= seen_columns).then_some(declared_columns),
150 more_rows: more_rows || declared_rows > first_row + ROWS_PER_PAGE,
151 more_columns: more_columns || declared_columns > first_column + COLUMNS_PER_PAGE,
152 rows,
153 first_row,
154 first_column,
155 })
156}
157
158/// The whole-workbook path, for the formats with no cell-at-a-time reader:
159/// xls, xlsb and ods. All three are bounded by the upload limit and by their
160/// own row ceilings, so the range fits in memory in a way an xlsx need not.
161fn read_whole(
162 bytes: Vec<u8>,
163 index: usize,
164 row_page: usize,
165 column_page: usize,
166) -> Option<Sheet> {
167 let mut book = open_workbook_auto_from_rs(Cursor::new(bytes)).ok()?;
168 let names = book.sheet_names();
169 if names.is_empty() {
170 return None;
171 }
172 let index = if index < names.len() { index } else { 0 };
173 let range = book.worksheet_range(&names[index]).ok()?;
174 let total_rows = range.height();
175 let total_columns = range.width();
176 let (first_row, first_column) = (row_page * ROWS_PER_PAGE, column_page * COLUMNS_PER_PAGE);
177 let rows: Vec<Vec<String>> = range
178 .rows()
179 .skip(first_row)
180 .take(ROWS_PER_PAGE)
181 .map(|row| {
182 row.iter()
183 .skip(first_column)
184 .take(COLUMNS_PER_PAGE)
185 .map(cell)
186 .collect()
187 })
188 .collect();
189 Some(Sheet {
190 names,
191 index,
192 rows,
193 first_row,
194 first_column,
195 // Nothing is declared here: the whole range was read, so its size is
196 // measured rather than believed.
197 total_rows: Some(total_rows),
198 total_columns: Some(total_columns),
199 more_rows: total_rows > first_row + ROWS_PER_PAGE,
200 more_columns: total_columns > first_column + COLUMNS_PER_PAGE,
201 })
202}
203
204/// One cell as the table shows it. Excel keeps a date as the number of days
205/// since 1899-12-30 and a duration as a fraction of one day, so both would
206/// print as a bare float without this; everything else is its own `Display`,
207/// and an empty cell is an empty string rather than a placeholder.
208fn cell(data: &Data) -> String {
209 match data {
210 Data::DateTime(stamp) if stamp.is_duration() => {
211 let total = (stamp.as_f64() * 86_400.0).round() as i64;
212 format!(
213 "{}:{:02}:{:02}",
214 total / 3600,
215 (total / 60) % 60,
216 total % 60
217 )
218 }
219 Data::DateTime(stamp) => {
220 let (year, month, day, hour, minute, second, _) = stamp.to_ymd_hms_milli();
221 if (hour, minute, second) == (0, 0, 0) {
222 format!("{year:04}-{month:02}-{day:02}")
223 } else {
224 format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}")
225 }
226 }
227 other => other.to_string(),
228 }
229}
230
231/// The spreadsheet name of a zero-based column: `A`, `Z`, `AA`, `AB`. The
232/// grid draws these across the top so a cell can be named out loud without
233/// guessing whether the sheet's first row is a header.
234pub(crate) fn column_name(index: usize) -> String {
235 let mut name = Vec::new();
236 let mut left = index;
237 loop {
238 name.push(b'A' + (left % 26) as u8);
239 if left < 26 {
240 break;
241 }
242 left = left / 26 - 1;
243 }
244 name.reverse();
245 String::from_utf8(name).unwrap_or_default()
246}
247
248#[cfg(test)]
249mod tests {
250 use super::*;
251 use calamine::{ExcelDateTime, ExcelDateTimeType};
252
253 #[test]
254 fn empty_cell_is_empty_string() {
255 assert_eq!(cell(&Data::Empty), "");
256 }
257
258 #[test]
259 fn a_whole_number_keeps_no_decimal_point() {
260 assert_eq!(cell(&Data::Float(1.0)), "1");
261 assert_eq!(cell(&Data::Int(42)), "42");
262 }
263
264 #[test]
265 fn a_date_reads_as_a_date_not_a_serial_number() {
266 let stamp = ExcelDateTime::new(45943.0, ExcelDateTimeType::DateTime, false);
267 assert_eq!(cell(&Data::DateTime(stamp)), "2025-10-13");
268 }
269
270 #[test]
271 fn a_time_of_day_rides_along_with_the_date() {
272 let stamp = ExcelDateTime::new(45943.5, ExcelDateTimeType::DateTime, false);
273 assert_eq!(cell(&Data::DateTime(stamp)), "2025-10-13 12:00");
274 }
275
276 #[test]
277 fn a_duration_reads_as_a_clock() {
278 let stamp = ExcelDateTime::new(0.5, ExcelDateTimeType::TimeDelta, false);
279 assert_eq!(cell(&Data::DateTime(stamp)), "12:00:00");
280 }
281
282 #[test]
283 fn columns_carry_past_z() {
284 assert_eq!(column_name(0), "A");
285 assert_eq!(column_name(25), "Z");
286 assert_eq!(column_name(26), "AA");
287 assert_eq!(column_name(27), "AB");
288 assert_eq!(column_name(51), "AZ");
289 assert_eq!(column_name(52), "BA");
290 assert_eq!(column_name(701), "ZZ");
291 assert_eq!(column_name(702), "AAA");
292 }
293
294 /// The window is what keeps a workbook of any size from becoming a page
295 /// of that size — and on the streamed path, from being read at all past
296 /// the rows it draws.
297 #[test]
298 fn a_page_holds_one_window_and_the_next_page_holds_the_next() {
299 let bytes = include_bytes!("../tests/fixtures/tall.xlsx").to_vec();
300 let first = read(bytes.clone(), 0, 0, 0).expect("the workbook opens");
301 assert_eq!(first.rows.len(), ROWS_PER_PAGE);
302 // This fixture declares no dimension, the way plenty of writers
303 // leave one out, so its size is not counted — but the next window is
304 // still known to be there, because a cell arrived in it.
305 assert_eq!(first.total_rows, None);
306 assert!(first.more_rows);
307 assert_eq!(first.first_row, 0);
308 assert_eq!(first.rows[0][0], "Row 1");
309 assert_eq!(first.rows[ROWS_PER_PAGE - 1][0], format!("Row {ROWS_PER_PAGE}"));
310
311 let third = read(bytes.clone(), 0, 2, 0).expect("the workbook opens");
312 assert_eq!(third.first_row, 2 * ROWS_PER_PAGE);
313 assert_eq!(
314 third.rows[0][0],
315 format!("Row {}", 2 * ROWS_PER_PAGE + 1)
316 );
317
318 // A page nobody links to — typed into the query string — is the
319 // empty window it names, with the step back to a real one still
320 // there. Nothing pretends it was a different page.
321 let past_the_end = read(bytes, 0, 9_000, 0).expect("the workbook opens");
322 assert!(past_the_end.rows.is_empty());
323 assert!(!past_the_end.more_rows);
324 }
325
326 /// A wide sheet pages sideways the same way, and the window's own corner
327 /// is what the grid labels its edges from.
328 #[test]
329 fn columns_page_the_same_way_rows_do() {
330 let bytes = include_bytes!("../tests/fixtures/wide.xlsx").to_vec();
331 let first = read(bytes.clone(), 0, 0, 0).expect("the workbook opens");
332 assert_eq!(first.total_columns, Some(40));
333 assert!(first.more_columns);
334 assert_eq!(first.rows[0].len(), COLUMNS_PER_PAGE);
335 assert_eq!(first.rows[0][0], "Col A");
336
337 let second = read(bytes, 0, 0, 1).expect("the workbook opens");
338 assert_eq!(second.first_column, COLUMNS_PER_PAGE);
339 assert_eq!(
340 second.rows[0][0],
341 format!("Col {}", column_name(COLUMNS_PER_PAGE))
342 );
343 }
344
345 #[test]
346 fn bytes_that_are_not_a_workbook_have_no_sheet() {
347 assert!(read(b"not a workbook at all".to_vec(), 0, 0, 0).is_none());
348 }
349}