Skip to main content

sheetkit_core/workbook/
mod.rs

1//! Workbook file I/O: reading and writing `.xlsx` files.
2//!
3//! An `.xlsx` file is a ZIP archive containing XML parts. This module provides
4//! [`Workbook`] which holds the parsed XML structures in memory and can
5//! serialize them back to a valid `.xlsx` file.
6
7use std::collections::{HashMap, HashSet};
8use std::io::{Read as _, Write as _};
9use std::path::Path;
10use std::sync::OnceLock;
11
12use serde::Serialize;
13use sheetkit_xml::chart::ChartSpace;
14use sheetkit_xml::comments::Comments;
15use sheetkit_xml::content_types::{
16    mime_types, ContentTypeDefault, ContentTypeOverride, ContentTypes,
17};
18
19/// The OOXML package format, determined by the workbook content type in
20/// `[Content_Types].xml`. Controls which content type string is emitted for
21/// `xl/workbook.xml` on save.
22#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
23pub enum WorkbookFormat {
24    /// Standard spreadsheet (.xlsx).
25    #[default]
26    Xlsx,
27    /// Macro-enabled spreadsheet (.xlsm).
28    Xlsm,
29    /// Template (.xltx).
30    Xltx,
31    /// Macro-enabled template (.xltm).
32    Xltm,
33    /// Macro-enabled add-in (.xlam).
34    Xlam,
35}
36
37impl WorkbookFormat {
38    /// Infer the format from a workbook content type string found in
39    /// `[Content_Types].xml`.
40    pub fn from_content_type(ct: &str) -> Option<Self> {
41        match ct {
42            mime_types::WORKBOOK => Some(Self::Xlsx),
43            mime_types::WORKBOOK_MACRO => Some(Self::Xlsm),
44            mime_types::WORKBOOK_TEMPLATE => Some(Self::Xltx),
45            mime_types::WORKBOOK_TEMPLATE_MACRO => Some(Self::Xltm),
46            mime_types::WORKBOOK_ADDIN_MACRO => Some(Self::Xlam),
47            _ => None,
48        }
49    }
50
51    /// Infer the format from a file extension (case-insensitive, without the
52    /// leading dot). Returns `None` for unrecognized extensions.
53    pub fn from_extension(ext: &str) -> Option<Self> {
54        match ext.to_ascii_lowercase().as_str() {
55            "xlsx" => Some(Self::Xlsx),
56            "xlsm" => Some(Self::Xlsm),
57            "xltx" => Some(Self::Xltx),
58            "xltm" => Some(Self::Xltm),
59            "xlam" => Some(Self::Xlam),
60            _ => None,
61        }
62    }
63
64    /// Return the OOXML content type string for this format.
65    pub fn content_type(self) -> &'static str {
66        match self {
67            Self::Xlsx => mime_types::WORKBOOK,
68            Self::Xlsm => mime_types::WORKBOOK_MACRO,
69            Self::Xltx => mime_types::WORKBOOK_TEMPLATE,
70            Self::Xltm => mime_types::WORKBOOK_TEMPLATE_MACRO,
71            Self::Xlam => mime_types::WORKBOOK_ADDIN_MACRO,
72        }
73    }
74}
75
76use sheetkit_xml::drawing::{MarkerType, WsDr};
77use sheetkit_xml::relationships::{self, rel_types, Relationship, Relationships};
78use sheetkit_xml::shared_strings::Sst;
79use sheetkit_xml::styles::StyleSheet;
80use sheetkit_xml::workbook::{WorkbookProtection, WorkbookXml};
81use sheetkit_xml::worksheet::{Cell, CellFormula, CellTypeTag, DrawingRef, Row, WorksheetXml};
82use zip::write::SimpleFileOptions;
83use zip::CompressionMethod;
84
85use crate::cell::CellValue;
86use crate::chart::ChartConfig;
87use crate::comment::CommentConfig;
88use crate::conditional::ConditionalFormatRule;
89use crate::error::{Error, Result};
90use crate::image::ImageConfig;
91use crate::pivot::{PivotTableConfig, PivotTableInfo};
92use crate::protection::WorkbookProtectionConfig;
93use crate::sst::SharedStringTable;
94use crate::threaded_comment::{PersonData, PersonInput, ThreadedCommentData, ThreadedCommentInput};
95use crate::utils::cell_ref::{cell_name_to_coordinates, column_name_to_number};
96use crate::utils::constants::MAX_CELL_CHARS;
97use crate::validation::DataValidationConfig;
98use crate::workbook_paths::{
99    default_relationships, relationship_part_path, relative_relationship_target,
100    resolve_relationship_target,
101};
102
103#[path = "aux_parts.rs"]
104pub(crate) mod aux;
105pub(crate) mod budget;
106mod cell_ops;
107mod data;
108mod drawing;
109mod features;
110mod io;
111pub mod open_options;
112pub(crate) mod package_reader;
113mod sheet_ops;
114mod source;
115
116pub use budget::OpenLimits;
117pub use open_options::{AuxParts, DateInterpretation, OpenOptions, ReadMode};
118pub(crate) use source::PackageSource;
119
120struct WorksheetSpoolWriter {
121    writer: std::io::BufWriter<std::fs::File>,
122    error: Option<Error>,
123    written: u64,
124    limit: u64,
125}
126
127impl std::fmt::Write for WorksheetSpoolWriter {
128    fn write_str(&mut self, value: &str) -> std::fmt::Result {
129        use std::io::Write as _;
130        if self.error.is_some() {
131            return Err(std::fmt::Error);
132        }
133        let amount = u64::try_from(value.len()).unwrap_or(u64::MAX);
134        let observed = self.written.saturating_add(amount);
135        if observed > self.limit {
136            let metadata = crate::resource::ResourceLimitError::exceeded(
137                crate::resource::ResourceOperation::StreamRead,
138                crate::resource::ResourceCategory::Streaming,
139                crate::resource::ResourceDimension::XmlBytes,
140                self.limit,
141                self.limit.saturating_add(1),
142                Some(crate::resource::ResourceStage::Serialize),
143            )
144            .expect("worksheet spool overflow must exceed its finite limit");
145            self.error = Some(Error::ResourceLimitExceeded(metadata));
146            return Err(std::fmt::Error);
147        }
148        if let Err(error) = self.writer.write_all(value.as_bytes()) {
149            self.error = Some(Error::Io(error));
150            return Err(std::fmt::Error);
151        }
152        self.written = observed;
153        Ok(())
154    }
155}
156
157fn spool_worksheet_xml(worksheet: &WorksheetXml, limit: u64) -> Result<std::fs::File> {
158    use serde::Serialize as _;
159    use std::io::{Seek as _, Write as _};
160
161    let file = tempfile::tempfile()?;
162    let mut output = WorksheetSpoolWriter {
163        writer: std::io::BufWriter::new(file),
164        error: None,
165        written: 0,
166        limit,
167    };
168    let result = worksheet.serialize(quick_xml::se::Serializer::new(&mut output));
169    if let Some(error) = output.error {
170        return Err(error);
171    }
172    result.map_err(|error| Error::XmlParse(error.to_string()))?;
173    output.writer.flush()?;
174    let mut file = output
175        .writer
176        .into_inner()
177        .map_err(|error| Error::Io(error.into_error()))?;
178    file.seek(std::io::SeekFrom::Start(0))?;
179    Ok(file)
180}
181
182/// Helper to initialize an `OnceLock<WorksheetXml>` with a value at
183/// construction time. Avoids repeating the `set`+`unwrap` pattern.
184pub(crate) fn initialized_lock(ws: WorksheetXml) -> OnceLock<WorksheetXml> {
185    let lock = OnceLock::new();
186    let _ = lock.set(ws);
187    lock
188}
189
190/// XML declaration prepended to every XML part in the package.
191const XML_DECLARATION: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>"#;
192
193/// In-memory representation of an `.xlsx` workbook.
194pub struct Workbook {
195    format: WorkbookFormat,
196    content_types: ContentTypes,
197    package_rels: Relationships,
198    workbook_xml: WorkbookXml,
199    /// Original `xl/workbook.xml` bytes retained for clean-owner passthrough.
200    raw_workbook_xml: Option<Vec<u8>>,
201    /// Typed state parsed from `raw_workbook_xml`, used for save-time dirty detection.
202    workbook_xml_baseline: Option<WorkbookXml>,
203    workbook_rels: Relationships,
204    /// Per-sheet worksheet XML, stored as `(name, OnceLock<WorksheetXml>)`.
205    /// When a sheet is eagerly parsed, the `OnceLock` is initialized at open
206    /// time. When a sheet is deferred in lazy mode, the lock is empty and the
207    /// first call to [`worksheet_ref`] or [`worksheet_mut`] hydrates it on
208    /// demand. Original bytes are retained in `raw_sheet_xml` in either case.
209    worksheets: Vec<(String, OnceLock<WorksheetXml>)>,
210    stylesheet: StyleSheet,
211    sst_runtime: SharedStringTable,
212    /// Per-sheet comments, parallel to the `worksheets` vector.
213    sheet_comments: Vec<Option<Comments>>,
214    /// Chart parts: (zip path like "xl/charts/chart1.xml", ChartSpace data).
215    charts: Vec<(String, ChartSpace)>,
216    /// Chart parts preserved as raw XML when typed parsing is not supported.
217    raw_charts: Vec<(String, Vec<u8>)>,
218    /// Drawing parts: (zip path like "xl/drawings/drawing1.xml", WsDr data).
219    drawings: Vec<(String, WsDr)>,
220    /// Original bytes for chart, drawing, and drawing relationship parts.
221    /// Clean entries take precedence over typed serialization on save.
222    raw_graph_parts: HashMap<String, Vec<u8>>,
223    /// Graph part paths whose typed owner was mutated after opening.
224    dirty_graph_parts: HashSet<String>,
225    /// Image parts: (zip path like "xl/media/image1.png", raw bytes).
226    images: Vec<(String, Vec<u8>)>,
227    /// Maps sheet index -> drawing index in `drawings`.
228    #[allow(dead_code)]
229    worksheet_drawings: HashMap<usize, usize>,
230    /// Per-sheet worksheet relationship files.
231    worksheet_rels: HashMap<usize, Relationships>,
232    /// Per-drawing relationship files: drawing_index -> Relationships.
233    drawing_rels: HashMap<usize, Relationships>,
234    /// Core document properties (docProps/core.xml).
235    core_properties: Option<sheetkit_xml::doc_props::CoreProperties>,
236    /// Extended/application properties (docProps/app.xml).
237    app_properties: Option<sheetkit_xml::doc_props::ExtendedProperties>,
238    /// Custom properties (docProps/custom.xml).
239    custom_properties: Option<sheetkit_xml::doc_props::CustomProperties>,
240    /// Original document-property bytes keyed independently by ZIP path.
241    raw_doc_props: HashMap<String, Vec<u8>>,
242    /// Document-property paths whose typed owner was mutated after opening.
243    dirty_doc_props: HashSet<String>,
244    /// Pivot table parts: (zip path, PivotTableDefinition data).
245    pivot_tables: Vec<(String, sheetkit_xml::pivot_table::PivotTableDefinition)>,
246    /// Pivot cache definition parts: (zip path, PivotCacheDefinition data).
247    pivot_cache_defs: Vec<(String, sheetkit_xml::pivot_cache::PivotCacheDefinition)>,
248    /// Pivot cache records parts: (zip path, PivotCacheRecords data).
249    pivot_cache_records: Vec<(String, sheetkit_xml::pivot_cache::PivotCacheRecords)>,
250    /// Raw theme XML bytes from xl/theme/theme1.xml (preserved for round-trip).
251    theme_xml: Option<Vec<u8>>,
252    /// Parsed theme colors from the theme XML.
253    theme_colors: sheetkit_xml::theme::ThemeColors,
254    /// Per-sheet sparkline configurations, parallel to the `worksheets` vector.
255    sheet_sparklines: Vec<Vec<crate::sparkline::SparklineConfig>>,
256    /// Whether each sheet's sparkline configuration has been materialized.
257    sheet_sparklines_hydrated: Vec<bool>,
258    /// Per-sheet VML drawing bytes (for legacy comment rendering), parallel to `worksheets`.
259    /// `None` means no VML part exists for that sheet.
260    sheet_vml: Vec<Option<Vec<u8>>>,
261    /// ZIP entries not recognized by the parser, preserved for round-trip fidelity.
262    /// Each entry is (zip_path, raw_bytes).
263    unknown_parts: Vec<(String, Vec<u8>)>,
264    /// Typed index of auxiliary parts deferred during Lazy/Stream open.
265    /// Stores raw bytes grouped by category (comments, charts, doc props, etc.)
266    /// and supports on-demand hydration with dirty tracking.
267    deferred_parts: aux::DeferredAuxParts,
268    /// Raw VBA project binary blob (`xl/vbaProject.bin`), preserved for round-trip
269    /// and used for VBA module extraction. `None` for non-macro workbooks.
270    vba_blob: Option<Vec<u8>>,
271    /// Table parts: (zip path like "xl/tables/table1.xml", TableXml data, sheet_index).
272    tables: Vec<(String, sheetkit_xml::table::TableXml, usize)>,
273    /// Original sheet XML bytes, parallel to `worksheets`.
274    /// Opened sheets retain `Some(bytes)` for exact clean-owner passthrough,
275    /// whether parsed eagerly, filtered out, or deferred in Lazy/Stream mode.
276    raw_sheet_xml: Vec<Option<Vec<u8>>>,
277    /// Worksheet-level extension fragments retained independently from the
278    /// full XML source for opaque sparkline/slicer metadata preservation.
279    raw_sheet_extensions: Vec<Option<Vec<u8>>>,
280    /// Per-sheet dirty flag, parallel to `worksheets`. A sheet is marked
281    /// dirty when it is mutated (via `worksheet_mut`, `set_cell_value`, etc.).
282    /// Clean sheets with available raw bytes are written via passthrough on
283    /// save, avoiding serialization overhead.
284    sheet_dirty: Vec<bool>,
285    /// Whether each sheet was included by `OpenOptions::sheets`.
286    /// Excluded sheets keep an empty typed placeholder while their original
287    /// compressed package entry remains available for clean passthrough.
288    sheet_included: Vec<bool>,
289    /// Whether the `OnceLock` contains the real typed worksheet rather than
290    /// an empty placeholder used for an excluded sheet.
291    sheet_materialized: Vec<bool>,
292    /// Whether the sheet still maps to an entry in `package_source`.
293    /// Newly created or copied sheets must never fall back to that archive.
294    sheet_package_backed: Vec<bool>,
295    /// Slicer definition parts: (zip path, SlicerDefinitions data).
296    slicer_defs: Vec<(String, sheetkit_xml::slicer::SlicerDefinitions)>,
297    /// Slicer cache definition parts: (zip path, raw XML string).
298    slicer_caches: Vec<(String, sheetkit_xml::slicer::SlicerCacheDefinition)>,
299    /// Per-sheet threaded comments (Excel 2019+), parallel to the `worksheets` vector.
300    sheet_threaded_comments: Vec<Option<sheetkit_xml::threaded_comment::ThreadedComments>>,
301    /// Person list shared across all sheets (for threaded comment authors).
302    person_list: sheetkit_xml::threaded_comment::PersonList,
303    /// Per-sheet form control configurations, parallel to `worksheets`.
304    sheet_form_controls: Vec<Vec<crate::control::FormControlConfig>>,
305    /// Tracks sheets whose control graph was intentionally changed.
306    sheet_controls_dirty: Vec<bool>,
307    /// O(1) sheet name -> index lookup cache. Must be kept in sync with
308    /// `worksheets` via [`rebuild_sheet_index`].
309    sheet_name_index: HashMap<String, usize>,
310    /// Streamed sheet data keyed by sheet index. During save, these sheets
311    /// are written by streaming from their temp files instead of serializing
312    /// the (empty placeholder) WorksheetXml.
313    streamed_sheets: HashMap<usize, crate::stream::StreamedSheetData>,
314    /// Backing storage for the xlsx package, retained for lazy part access.
315    #[allow(dead_code)]
316    package_source: Option<PackageSource>,
317    /// Read mode used when this workbook was opened.
318    read_mode: ReadMode,
319    /// Optional row limit from `OpenOptions::sheet_rows`, applied during
320    /// on-demand hydration of deferred sheets.
321    sheet_rows_limit: Option<u32>,
322    /// Finite ceiling for serializing a dirty or new worksheet into a
323    /// streaming-reader spool.
324    worksheet_spool_limit: u64,
325    /// Controls whether number cells carrying a date-like number format
326    /// should be surfaced as [`CellValue::Date`](crate::cell::CellValue::Date).
327    /// Sourced from [`OpenOptions::date_interpretation`].
328    date_interpretation: DateInterpretation,
329}
330
331impl Workbook {
332    /// Return the detected or assigned workbook format.
333    pub fn format(&self) -> WorkbookFormat {
334        self.format
335    }
336
337    /// Set the workbook format. This determines the content type written for
338    /// `xl/workbook.xml` on save.
339    pub fn set_format(&mut self, format: WorkbookFormat) {
340        self.format = format;
341    }
342
343    /// Get the 0-based index of a sheet by name. O(1) via HashMap.
344    pub(crate) fn sheet_index(&self, sheet: &str) -> Result<usize> {
345        self.sheet_name_index
346            .get(sheet)
347            .copied()
348            .ok_or_else(|| Error::SheetNotFound {
349                name: sheet.to_string(),
350            })
351    }
352
353    /// Discard streamed backing for an explicitly whole-sheet replacement.
354    pub(crate) fn invalidate_streamed(&mut self, idx: usize) {
355        self.streamed_sheets.remove(&idx);
356    }
357
358    /// Reject mutations that cannot preserve streamed rows.
359    pub(crate) fn reject_streamed_mutation(&self, idx: usize) -> Result<()> {
360        if self.streamed_sheets.contains_key(&idx) {
361            return Err(Error::StreamedSheetMutation {
362                sheet: self.worksheets[idx].0.clone(),
363            });
364        }
365        Ok(())
366    }
367
368    /// Mark a sheet as dirty (modified). Dirty sheets are always serialized
369    /// on save, even if raw bytes exist. Clean sheets can use raw-byte
370    /// passthrough for zero-cost round-trip.
371    pub(crate) fn mark_sheet_dirty(&mut self, idx: usize) {
372        if idx < self.sheet_dirty.len() {
373            self.sheet_dirty[idx] = true;
374        }
375    }
376
377    pub(crate) fn remember_raw_graph_part(&mut self, path: String, bytes: Vec<u8>) {
378        self.raw_graph_parts.insert(path, bytes);
379    }
380
381    pub(crate) fn mark_graph_part_dirty(&mut self, path: &str) {
382        self.dirty_graph_parts.insert(path.to_string());
383    }
384
385    pub(crate) fn mark_drawing_dirty(&mut self, drawing_idx: usize) {
386        if let Some((path, _)) = self.drawings.get(drawing_idx) {
387            self.dirty_graph_parts.insert(path.clone());
388        }
389    }
390
391    pub(crate) fn mark_drawing_relationships_dirty(&mut self, drawing_idx: usize) {
392        if let Some((path, _)) = self.drawings.get(drawing_idx) {
393            self.dirty_graph_parts.insert(relationship_part_path(path));
394        }
395    }
396
397    pub(crate) fn remove_graph_part(&mut self, path: &str) {
398        self.raw_graph_parts.remove(path);
399        self.dirty_graph_parts.remove(path);
400    }
401
402    fn clean_raw_graph_part(&self, path: &str) -> Option<&[u8]> {
403        if self.dirty_graph_parts.contains(path) {
404            None
405        } else {
406            self.raw_graph_parts.get(path).map(Vec::as_slice)
407        }
408    }
409
410    pub(crate) fn remember_raw_doc_prop(&mut self, path: String, bytes: Vec<u8>) {
411        self.raw_doc_props.insert(path, bytes);
412    }
413
414    pub(crate) fn mark_doc_prop_dirty(&mut self, path: &str) {
415        self.dirty_doc_props.insert(path.to_string());
416    }
417
418    fn clean_raw_doc_prop(&self, path: &str) -> Option<&[u8]> {
419        if self.dirty_doc_props.contains(path) {
420            None
421        } else {
422            self.raw_doc_props.get(path).map(Vec::as_slice)
423        }
424    }
425
426    /// Check whether a sheet has been marked dirty since opening.
427    #[cfg(test)]
428    pub(crate) fn is_sheet_dirty(&self, idx: usize) -> bool {
429        self.sheet_dirty.get(idx).copied().unwrap_or(false)
430    }
431
432    /// Get a mutable reference to the worksheet XML for the named sheet.
433    ///
434    /// Random-access mutation of streamed sheets is rejected because their
435    /// backing rows are not materialized in this worksheet XML.
436    pub(crate) fn worksheet_mut(&mut self, sheet: &str) -> Result<&mut WorksheetXml> {
437        let idx = self.sheet_index(sheet)?;
438        self.reject_streamed_mutation(idx)?;
439        self.ensure_hydrated(idx)?;
440        self.mark_sheet_dirty(idx);
441        Ok(self.worksheets[idx].1.get_mut().unwrap())
442    }
443
444    /// Get an immutable reference to the worksheet XML for the named sheet.
445    /// Deferred sheets are hydrated lazily via `OnceLock`.
446    pub(crate) fn worksheet_ref(&self, sheet: &str) -> Result<&WorksheetXml> {
447        let idx = self.sheet_index(sheet)?;
448        self.worksheet_ref_by_index(idx)
449    }
450
451    /// Get an immutable reference to the worksheet XML by index.
452    /// Deferred sheets are hydrated lazily via `OnceLock`.
453    pub(crate) fn worksheet_ref_by_index(&self, idx: usize) -> Result<&WorksheetXml> {
454        if let Some(ws) = self.worksheets[idx].1.get() {
455            return Ok(ws);
456        }
457        if !self.sheet_included.get(idx).copied().unwrap_or(true) {
458            return Ok(self.worksheets[idx].1.get_or_init(WorksheetXml::default));
459        }
460        // Hydrate from raw_sheet_xml on first access.
461        if let Some(Some(bytes)) = self.raw_sheet_xml.get(idx) {
462            let ws = io::deserialize_worksheet_xml_with_row_limit(
463                std::io::Cursor::new(bytes.as_slice()),
464                self.sheet_rows_limit,
465            )?;
466            Ok(self.worksheets[idx].1.get_or_init(|| ws))
467        } else if self.sheet_package_backed.get(idx).copied().unwrap_or(false)
468            && self.package_source.is_some()
469        {
470            let ws = self.deserialize_package_sheet(idx)?;
471            Ok(self.worksheets[idx].1.get_or_init(|| ws))
472        } else {
473            Err(Error::Internal(format!(
474                "sheet at index {} has no materialized or deferred data",
475                idx
476            )))
477        }
478    }
479
480    /// Public immutable reference to a worksheet's XML by sheet name.
481    /// Deferred sheets are hydrated lazily on first access.
482    pub fn worksheet_xml_ref(&self, sheet: &str) -> Result<&WorksheetXml> {
483        self.worksheet_ref(sheet)
484    }
485
486    /// Public immutable reference to the shared string table.
487    pub fn sst_ref(&self) -> &SharedStringTable {
488        &self.sst_runtime
489    }
490
491    /// Rebuild the sheet name -> index lookup after any structural change
492    /// to the worksheets vector.
493    pub(crate) fn rebuild_sheet_index(&mut self) {
494        self.sheet_name_index.clear();
495        for (i, (name, _ws_lock)) in self.worksheets.iter().enumerate() {
496            self.sheet_name_index.insert(name.clone(), i);
497        }
498    }
499
500    /// Ensure the sheet at the given index is hydrated (parsed from raw XML).
501    /// This is used by `&mut self` methods that need a mutable `OnceLock`
502    /// reference via `get_mut()`, which requires the lock to be initialized.
503    fn ensure_hydrated(&mut self, idx: usize) -> Result<()> {
504        if self.worksheets[idx].1.get().is_some() {
505            // OnceLock is set. If raw bytes are still present, this is a
506            // placeholder (filtered-out sheet with WorksheetXml::default()).
507            // Replace the placeholder with properly parsed data.
508            if !self.sheet_materialized.get(idx).copied().unwrap_or(true) {
509                if let Some(Some(bytes)) = self.raw_sheet_xml.get(idx) {
510                    let ws = io::deserialize_worksheet_xml_with_row_limit(
511                        std::io::Cursor::new(bytes.as_slice()),
512                        self.sheet_rows_limit,
513                    )?;
514                    *self.worksheets[idx].1.get_mut().unwrap() = ws;
515                    self.sheet_materialized[idx] = true;
516                } else if !self.sheet_included.get(idx).copied().unwrap_or(true)
517                    && self.sheet_package_backed.get(idx).copied().unwrap_or(false)
518                    && self.package_source.is_some()
519                {
520                    let ws = self.deserialize_package_sheet(idx)?;
521                    *self.worksheets[idx].1.get_mut().unwrap() = ws;
522                    self.sheet_materialized[idx] = true;
523                }
524            }
525            if self.sheet_included.get(idx).copied().unwrap_or(true) {
526                self.sheet_materialized[idx] = true;
527            }
528            return Ok(());
529        }
530        if let Some(Some(bytes)) = self.raw_sheet_xml.get(idx) {
531            let ws = io::deserialize_worksheet_xml_with_row_limit(
532                std::io::Cursor::new(bytes.as_slice()),
533                self.sheet_rows_limit,
534            )?;
535            let _ = self.worksheets[idx].1.set(ws);
536            self.sheet_materialized[idx] = true;
537            Ok(())
538        } else if self.sheet_package_backed.get(idx).copied().unwrap_or(false)
539            && self.package_source.is_some()
540        {
541            let ws = self.deserialize_package_sheet(idx)?;
542            let _ = self.worksheets[idx].1.set(ws);
543            self.sheet_materialized[idx] = true;
544            Ok(())
545        } else {
546            Err(Error::Internal(format!(
547                "sheet at index {} has no materialized or deferred data",
548                idx
549            )))
550        }
551    }
552
553    /// Hydrate if needed and return a mutable reference to the worksheet
554    /// at the given index. Callers must hold `&mut self`.
555    pub(crate) fn worksheet_mut_by_index(&mut self, idx: usize) -> Result<&mut WorksheetXml> {
556        self.reject_streamed_mutation(idx)?;
557        self.ensure_hydrated(idx)?;
558        self.mark_sheet_dirty(idx);
559        Ok(self.worksheets[idx].1.get_mut().unwrap())
560    }
561
562    fn deserialize_package_sheet(&self, idx: usize) -> Result<WorksheetXml> {
563        let source = self.package_source.as_ref().ok_or_else(|| {
564            Error::Internal(format!("sheet at index {idx} has no package source"))
565        })?;
566        let row_limit = self.sheet_rows_limit;
567        let worksheet = source.parse_xml_part(&self.sheet_part_path(idx), |reader| {
568            io::deserialize_worksheet_xml_with_row_limit(reader, row_limit)
569        })?;
570        io::validate_materialized_worksheet_table_parts(
571            &worksheet,
572            self.worksheet_rels.get(&idx),
573            &self.sheet_part_path(idx),
574        )?;
575        Ok(worksheet)
576    }
577
578    fn deserialize_package_sheet_for_save(&self, idx: usize) -> Result<WorksheetXml> {
579        let source = self.package_source.as_ref().ok_or_else(|| {
580            Error::Internal(format!("sheet at index {idx} has no package source"))
581        })?;
582        let worksheet = source.parse_xml_part(&self.sheet_part_path(idx), |reader| {
583            io::deserialize_worksheet_xml_with_row_limit(reader, None)
584        })?;
585        io::validate_materialized_worksheet_table_parts(
586            &worksheet,
587            self.worksheet_rels.get(&idx),
588            &self.sheet_part_path(idx),
589        )?;
590        Ok(worksheet)
591    }
592
593    /// Resolve the part path for a sheet index from workbook relationships.
594    /// Falls back to the default `xl/worksheets/sheet{N}.xml` naming.
595    pub(crate) fn sheet_part_path(&self, sheet_idx: usize) -> String {
596        if let Some(sheet_entry) = self.workbook_xml.sheets.sheets.get(sheet_idx) {
597            if let Some(rel) = self
598                .workbook_rels
599                .relationships
600                .iter()
601                .find(|r| r.id == sheet_entry.r_id && r.rel_type == rel_types::WORKSHEET)
602            {
603                return resolve_relationship_target("xl/workbook.xml", &rel.target);
604            }
605        }
606        format!("xl/worksheets/sheet{}.xml", sheet_idx + 1)
607    }
608
609    fn owned_drawing_path(&self, sheet_idx: usize) -> Option<String> {
610        let sheet_path = self.sheet_part_path(sheet_idx);
611        self.worksheet_rels
612            .get(&sheet_idx)?
613            .relationships
614            .iter()
615            .find(|relationship| relationship.rel_type == rel_types::DRAWING)
616            .map(|relationship| resolve_relationship_target(&sheet_path, &relationship.target))
617    }
618
619    fn ensure_owned_drawing_hydratable(&self, sheet_idx: usize) -> Result<()> {
620        let Some(owned_path) = self.owned_drawing_path(sheet_idx) else {
621            return Ok(());
622        };
623        if self
624            .worksheet_drawings
625            .get(&sheet_idx)
626            .and_then(|drawing_idx| self.drawings.get(*drawing_idx))
627            .is_some_and(|(path, _)| *path == owned_path)
628        {
629            return Ok(());
630        }
631        if let Some(bytes) = self
632            .deferred_parts
633            .get_path(aux::AuxCategory::Drawings, &owned_path)
634        {
635            return quick_xml::de::from_reader::<_, WsDr>(bytes)
636                .map(|_| ())
637                .map_err(|_| {
638                    Error::InvalidArgument(format!(
639                        "cannot modify worksheet drawing '{owned_path}' because it is not parsed"
640                    ))
641                });
642        }
643        Err(Error::InvalidArgument(format!(
644            "cannot modify worksheet drawing '{owned_path}' because it is not parsed"
645        )))
646    }
647
648    fn ensure_drawing_relationships_hydratable(&self, sheet_idx: usize) -> Result<()> {
649        self.ensure_owned_drawing_hydratable(sheet_idx)?;
650        let Some(drawing_path) = self.owned_drawing_path(sheet_idx) else {
651            return Ok(());
652        };
653        let rels_path = relationship_part_path(&drawing_path);
654        if self
655            .worksheet_drawings
656            .get(&sheet_idx)
657            .is_some_and(|drawing_idx| self.drawing_rels.contains_key(drawing_idx))
658        {
659            return Ok(());
660        }
661        if let Some(bytes) = self
662            .deferred_parts
663            .get_path(aux::AuxCategory::DrawingRels, &rels_path)
664        {
665            return quick_xml::de::from_reader::<_, Relationships>(bytes)
666                .map(|_| ())
667                .map_err(|_| {
668                    Error::InvalidArgument(format!(
669                        "cannot modify drawing relationships '{rels_path}' because they are not parsed"
670                    ))
671                });
672        }
673        if self.clean_raw_graph_part(&rels_path).is_some() {
674            return Err(Error::InvalidArgument(format!(
675                "cannot modify drawing relationships '{rels_path}' because they are not parsed"
676            )));
677        }
678        Ok(())
679    }
680
681    pub(crate) fn ensure_owned_drawing_parsed(&self, sheet_idx: usize) -> Result<Option<usize>> {
682        let Some(owned_path) = self.owned_drawing_path(sheet_idx) else {
683            return Ok(None);
684        };
685        let drawing_idx = self
686            .worksheet_drawings
687            .get(&sheet_idx)
688            .copied()
689            .filter(|drawing_idx| {
690                self.drawings
691                    .get(*drawing_idx)
692                    .is_some_and(|(path, _)| *path == owned_path)
693            })
694            .ok_or_else(|| {
695                Error::InvalidArgument(format!(
696                    "cannot modify worksheet drawing '{owned_path}' because it is not parsed"
697                ))
698            })?;
699        Ok(Some(drawing_idx))
700    }
701
702    pub(crate) fn ensure_drawing_relationships_editable(
703        &self,
704        sheet_idx: usize,
705    ) -> Result<Option<usize>> {
706        let Some(drawing_idx) = self.ensure_owned_drawing_parsed(sheet_idx)? else {
707            return Ok(None);
708        };
709        let drawing_path = &self.drawings[drawing_idx].0;
710        let rels_path = relationship_part_path(drawing_path);
711        if self.clean_raw_graph_part(&rels_path).is_some()
712            && !self.drawing_rels.contains_key(&drawing_idx)
713        {
714            return Err(Error::InvalidArgument(format!(
715                "cannot modify drawing relationships '{rels_path}' because they are not parsed"
716            )));
717        }
718        Ok(Some(drawing_idx))
719    }
720
721    /// Create a forward-only streaming reader for the named sheet.
722    ///
723    /// The reader processes worksheet XML row-by-row without materializing the
724    /// full DOM, enabling bounded-memory processing of large worksheets. The
725    /// workbook's shared string table and optional `sheet_rows` limit are
726    /// passed through to the reader.
727    ///
728    /// Clean package-backed sheets are decompressed into an anonymous spool;
729    /// dirty sheets are serialized directly into one. Neither path allocates a
730    /// second sheet-sized byte vector.
731    pub fn open_sheet_reader(
732        &self,
733        sheet: &str,
734    ) -> Result<
735        crate::stream_reader::SheetStreamReader<'_, crate::stream_reader::SheetReaderInput<'_>>,
736    > {
737        let idx = self.sheet_index(sheet)?;
738        let input = self.sheet_reader_input(idx)?;
739        Ok(
740            crate::stream_reader::SheetStreamReader::new(input, &self.sst_runtime)
741                .row_limit(self.sheet_rows_limit)
742                .date_promotion(self.date_interpretation, self.computed_style_is_date()),
743        )
744    }
745
746    /// Create an owned forward-only streaming reader for the named sheet.
747    ///
748    /// Unlike [`Self::open_sheet_reader`], the returned reader owns a disk-backed
749    /// source and an O(1) copy-on-write shared-string snapshot, so it has no
750    /// lifetime tied to the workbook. This is suitable for FFI contexts.
751    pub fn open_sheet_reader_owned(
752        &self,
753        sheet: &str,
754    ) -> Result<crate::stream_reader::OwnedSheetStreamReader> {
755        let idx = self.sheet_index(sheet)?;
756        let spool = self.sheet_reader_spool(idx)?;
757        let sst_snapshot = self.sst_runtime.clone_for_read();
758        Ok(
759            crate::stream_reader::OwnedSheetStreamReader::from_spool(spool, sst_snapshot)
760                .row_limit(self.sheet_rows_limit)
761                .date_promotion(self.date_interpretation, self.computed_style_is_date()),
762        )
763    }
764
765    /// Precompute, for each cellXf, whether its number format is a date
766    /// format. Used by streaming readers to decide whether to promote
767    /// `t="n"` cells to `CellValue::Date` under
768    /// [`DateInterpretation::NumFmt`].
769    ///
770    /// Returns an empty vector when the [`DateInterpretation::CellType`]
771    /// mode is active; stream readers short-circuit on interpretation
772    /// alone before consulting the lookup, so the empty allocation is a
773    /// cheap default and the lookup work is skipped entirely.
774    fn computed_style_is_date(&self) -> Vec<bool> {
775        if matches!(self.date_interpretation, DateInterpretation::CellType) {
776            return Vec::new();
777        }
778        crate::style::compute_style_is_date(&self.stylesheet)
779    }
780
781    /// Date-style lookup for read-only transfer encoders.
782    #[doc(hidden)]
783    pub fn transfer_date_style_lookup(&self) -> Vec<bool> {
784        self.computed_style_is_date()
785    }
786
787    fn sheet_reader_input(&self, idx: usize) -> Result<crate::stream_reader::SheetReaderInput<'_>> {
788        let dirty = self.sheet_dirty.get(idx).copied().unwrap_or(true);
789        let included = self.sheet_included.get(idx).copied().unwrap_or(true);
790        if included && !dirty {
791            if let Some(Some(bytes)) = self.raw_sheet_xml.get(idx) {
792                return Ok(crate::stream_reader::SheetReaderInput::Borrowed(
793                    std::io::Cursor::new(bytes.as_slice()),
794                ));
795            }
796            if self.sheet_package_backed.get(idx).copied().unwrap_or(false) {
797                if let Some(source) = &self.package_source {
798                    let spool = source.spool_xml_part(&self.sheet_part_path(idx))?;
799                    return Ok(crate::stream_reader::SheetReaderInput::Spool(
800                        std::io::BufReader::new(spool),
801                    ));
802                }
803            }
804        }
805
806        Ok(crate::stream_reader::SheetReaderInput::Spool(
807            std::io::BufReader::new(spool_worksheet_xml(
808                self.worksheet_ref_by_index(idx)?,
809                self.worksheet_spool_limit,
810            )?),
811        ))
812    }
813
814    fn sheet_reader_spool(&self, idx: usize) -> Result<std::fs::File> {
815        let dirty = self.sheet_dirty.get(idx).copied().unwrap_or(true);
816        let included = self.sheet_included.get(idx).copied().unwrap_or(true);
817        if included && !dirty {
818            if let Some(Some(bytes)) = self.raw_sheet_xml.get(idx) {
819                use std::io::{Seek as _, Write as _};
820                let mut spool = tempfile::tempfile()?;
821                spool.write_all(bytes)?;
822                spool.seek(std::io::SeekFrom::Start(0))?;
823                return Ok(spool);
824            }
825            if self.sheet_package_backed.get(idx).copied().unwrap_or(false) {
826                if let Some(source) = &self.package_source {
827                    return source.spool_xml_part(&self.sheet_part_path(idx));
828                }
829            }
830        }
831        spool_worksheet_xml(
832            self.worksheet_ref_by_index(idx)?,
833            self.worksheet_spool_limit,
834        )
835    }
836}