OpenXLSX 1.12.1
Modern C++ Excel Library (Fork of OpenXLSX by Kenneth Troldal Balslev)
Loading...
Searching...
No Matches
OpenXLSX::XLDocument Class Referencefinal

This class encapsulates the concept of an excel file. It is different from the XLWorkbook, in that an XLDocument holds an XLWorkbook together with its metadata, as well as methods for opening, closing and saving the document.
The XLDocument is the entrypoint for clients using the RapidXLSX library.. More...

#include <XLDocument.hpp>

Inheritance diagram for OpenXLSX::XLDocument:
OpenXLSX::XLPackageServices OpenXLSX::XLPackagePartFactory OpenXLSX::XLSharedStringTable

Data Structures

struct  SharedFormula

Public Types

using XLCellChangeListener = std::function<void(std::string_view sheetName, uint32_t row, uint16_t col, bool formulaChanged)>
 Listener for cell content changes (value or formula).

Public Member Functions

XLXmlData * getXmlData (XLInternalAccess, std::string_view path, bool doNotThrow=false)
const XLXmlData * getXmlData (XLInternalAccess, std::string_view path, bool doNotThrow=false) const
XLXmlData * addXmlData (XLInternalAccess, const std::string &path, const std::string &id, XLContentType type)
std::map< void *, std::unordered_map< uint32_t, SharedFormula > > & sharedFormulas (XLInternalAccess) const
 XLDocument (const IZipArchive &zipArchive=XLZipArchive())
 Default constructor. Initializes an empty document package with a default ZIP archive.
 XLDocument (std::string_view docPath, const IZipArchive &zipArchive=XLZipArchive())
 Path-based constructor. Loads an existing document or sets the target path for a new one.
 XLDocument (const std::string &docPath, const IZipArchive &zipArchive=XLZipArchive())
 Legacy string constructor. Maintained to resolve ambiguity with IZipArchive's template constructor when passing string literals or std::string.
 XLDocument (const XLDocument &other)=delete
 XLDocument (XLDocument &&other) noexcept=default
 ~XLDocument ()
XLDocument & operator= (const XLDocument &other)=delete
XLDocument & operator= (XLDocument &&other) noexcept=default
void showWarnings ()
void suppressWarnings ()
void open (std::string_view fileName)
 Open an existing .xlsx package. Uses std::string_view for zero-copy path processing.
void setMaxEntryUncompressedSize (size_t maxBytes)
 Cap uncompressed size for archive.getEntry() loads (0 = unlimited).
size_t maxEntryUncompressedSize () const
void open (std::string_view fileName, const std::string &password)
 Open an existing encrypted .xlsx package.
void create (std::string_view fileName, bool forceOverwrite=XLForceOverwrite)
 Initialize a new .xlsx package from a built-in template.
void create (const std::string &fileName)
 Create a new .xlsx file with the given name. Legacy interface.
void close ()
 Close the document and release underlying ZIP resources, ensuring file handles are closed properly.
void save ()
 Save changes to the original file path.
void addStreamedFile (std::string_view pathInZip, std::string_view tempFilePath)
void validatePackageInvariants () const
 Validate package-level OOXML invariants before serialization.
void saveAs (std::string_view fileName, bool forceOverwrite=XLForceOverwrite)
 Persistence to a new location.
void saveAs (std::string_view fileName, const std::string &password, bool forceOverwrite=XLForceOverwrite)
 Persistence to a new location with encryption.
void saveAs (const std::string &fileName)
 Save the document with a new name. Legacy interface.
std::string name () const
 Access filename to uniquely identify the document in the package.
const std::string & path () const
 Access the full filesystem path of the current document. [[nodiscard]] prevents ignoring the current path reference.
XLContentTypes & contentTypes () override
 Provides access to the [Content_Types].xml file, which defines the package structure and internal part mapping.
const XLContentTypes & contentTypes () const override
bool hasMacro () const
 Provides access to custom properties (metadata) that can be set for the document.
void deleteMacro ()
 Deletes the VBA macro project and all macro-related signatures/relationships from the document. This is typically used to sanitize a file before saving it as a standard .xlsx.
XLCustomProperties & customProperties ()
uint32_t nextTableId () const override
 Atomic table ID generator to ensure workbook-wide uniqueness for Excel table structures. [[nodiscard]] is used to enforce correct result consumption.
XLWorkbook workbook () const
 Get the underlying workbook object, containing worksheets and global data state. [[nodiscard]] prevents side-effect-free querying errors.
std::string property (XLProperty prop) const
 Fetch metadata property by type (e.g., Title, Creator).
void setProperty (XLProperty prop, std::string_view value)
 Update metadata property. Uses string_view to allow updating from literals without temporary allocations.
void deleteProperty (XLProperty theProperty)
 Remove specific metadata property.
 operator bool () const
bool isOpen () const
void setCompressionLevel (int level)
 Set the compression level for packing the document.
int compressionLevel () const
 Get the current compression level.
void setDefaultAuthor (const std::string &author)
 Set the default author for comments and notes.
std::string defaultAuthor () const
 Get the default author for comments and notes.
XLStyles & styles ()
 Provides access to shared document styles (fonts, fills, borders, cell formats).
const XLStyles & styles () const
void compactStyles ()
 Compact and deduplicate all styles across the workbook and all worksheets.
bool hasSheetRelationships (uint16_t sheetXmlNo, bool isChartsheet=false) const override
 Component presence checks, used to avoid unnecessary parsing of absent components in the package.
bool hasSheetVmlDrawing (uint16_t sheetXmlNo) const override
bool hasSheetComments (uint16_t sheetXmlNo) const override
bool hasSheetThreadedComments (uint16_t sheetXmlNo) const override
bool hasSheetDrawing (uint16_t sheetXmlNo) const override
bool hasSheetTables (uint16_t sheetXmlNo) const override
XLRelationships sheetRelationships (uint16_t sheetXmlNo, bool isChartsheet=false) override
XLDrawing sheetDrawing (uint16_t sheetXmlNo) override
XLDrawing createDrawing () override
XLDrawing drawing (std::string_view path) override
XLVmlDrawing sheetVmlDrawing (uint16_t sheetXmlNo) override
XLComments sheetComments (uint16_t sheetXmlNo) override
XLThreadedComments sheetThreadedComments (uint16_t sheetXmlNo) override
XLTables sheetTables (uint16_t sheetXmlNo) override
XLChart createChart (XLChartType type=XLChartType::Bar) override
class XLPivotTable createPivotTable ()
class XLPivotCacheDefinition createPivotCacheDefinition ()
class XLPivotCacheRecords createPivotCacheRecords (std::string_view cacheDefPath)
void deleteManagedXmlPart (std::string_view path)
 Remove a managed package XML part (archive entry, content type, in-memory XLXmlData).
std::string createTableSlicerCache (uint32_t tableId, uint32_t tableColumnId, std::string_view name, std::string_view sourceName) override
std::string findOrCreateTableSlicerCache (uint32_t tableId, uint32_t tableColumnId, std::string_view name, std::string_view sourceName) override
std::string createPivotSlicerCache (uint32_t pivotCacheId, uint32_t sheetId, std::string_view pivotTableName, std::string_view name, std::string_view sourceName) override
std::string findOrCreatePivotSlicerCache (uint32_t pivotCacheId, uint32_t sheetId, std::string_view pivotTableName, std::string_view name, std::string_view sourceName) override
std::string createSlicer (std::string_view name, std::string_view cacheName, std::string_view caption, std::string_view existingSlicerFile={}) override
void deleteSlicerFileAndOrphanCache (const std::string &name) override
std::string addImage (std::string_view name, std::string_view data) override
 Insert image into the archive's media folder. Uses string_view for zero-copy data transfer.
std::string addImage (std::string_view name, gsl::span< const uint8_t > data) override
std::string getImage (std::string_view path) const override
 Fetch raw image data from the document archive (xl/media/).
XLRelationships drawingRelationships (std::string_view drawingPath) override
XLRelationships xmlRelationships (std::string_view xmlPath) override
 Get relationships for an arbitrary XML file (e.g. pivot tables).
XLRelationships & workbookRelationships () override
 Get workbook relationships.
IZipArchive & archive () override
 Access the low-level ZIP archive for advanced package manipulation. [[nodiscard]] is used to prevent state-querying errors.
const IZipArchive & archive () const override
XLXmlData * findXmlPart (std::string_view path, bool doNotThrow=false) override
 Locate a managed XML part by package path (e.g. "xl/pivotCache/pivotCacheDefinition1.xml").
const XLXmlData * findXmlPart (std::string_view path, bool doNotThrow=false) const override
XLXmlData * emplaceXmlPart (const std::string &path, const std::string &id, XLContentType type) override
 Create and register a new managed XML part in the document's part list.
XLAppProperties & appProperties ()
 Access application-specific properties (metadata). [[nodiscard]] is used to prevent state-querying errors.
const XLAppProperties & appProperties () const
XLProperties & coreProperties ()
 Access core document metadata properties. [[nodiscard]] is used to prevent state-querying errors.
const XLProperties & coreProperties () const
bool validateSheetName (std::string_view sheetName, bool throwOnInvalid=false)
 Ensure worksheet names adhere to Excel's naming rules.
bool execCommand (const XLCommand &command)
XLQuery execQuery (const XLQuery &query) const
 Execute a state-querying operation without modifying the document. [[nodiscard]] is used to prevent state-querying errors.
XLQuery execQuery (const XLQuery &query)
void setSavingDeclaration (XLXmlSavingDeclaration const &savingDeclaration)
const XLSharedStrings & sharedStrings () const
 Access the workbook's central Shared String Table (SST). The SST reduces file size by deduplicating text across the entire package.
const XLSharedStringTable & sharedStringTable () const
 Read-only SST port (index ↔ string lookups only).
int32_t stringCount () const override
int32_t getStringIndex (std::string_view str) const override
 Look up an existing string's index.
bool stringExists (std::string_view str) const override
const char * getString (int32_t index) const override
 Resolve an SST index to a null-terminated C string.
std::string_view getStringView (int32_t index) const override
 Resolve an SST index to a string_view into the arena/cache.
bool hasPersons () const
 Check if the document has a persons metadata file.
XLPersons & persons ()
 Access the persons metadata for threaded comments.
void cleanupSharedStrings ()
 Prune unused strings from the SST and reindex referencing cells. Essential for minimizing file size and memory footprint in long-lived or large documents.
void setFormulaNeedsRecalculation (bool status=true)
 Marks the document to require formula recalculation on load.
void registerCellChangeListener (const void *token, XLCellChangeListener listener)
 Register a cell-change listener. token must be unique (e.g. this of the engine).
void unregisterCellChangeListener (const void *token)
 Remove a previously registered listener.
void notifyCellChanged (std::string_view sheetName, uint32_t row, uint16_t col, bool formulaChanged)
 Notify listeners that a cell changed (value and/or formula).
std::string extractXmlFromArchive (std::string_view path)
 Fetch raw XML content for a specific package path. Used internally for lazily loading components on demand, or for advanced testing/inspection.
std::shared_mutex & mutex () const
 Get the document-level mutex for thread-safe operations.
Public Member Functions inherited from OpenXLSX::XLPackageServices
virtual ~XLPackageServices ()=default
Public Member Functions inherited from OpenXLSX::XLPackagePartFactory
virtual ~XLPackagePartFactory ()=default
Public Member Functions inherited from OpenXLSX::XLSharedStringTable
virtual ~XLSharedStringTable ()=default

Protected Member Functions

XLXmlData * getXmlData (std::string_view path, bool doNotThrow=false)
 Provide access to managed XML data nodes, enabling centralized XML state management. doNotThrow allows safe querying when a component's presence is uncertain.
const XLXmlData * getXmlData (std::string_view path, bool doNotThrow=false) const
bool hasXmlData (std::string_view path) const

Detailed Description

This class encapsulates the concept of an excel file. It is different from the XLWorkbook, in that an XLDocument holds an XLWorkbook together with its metadata, as well as methods for opening, closing and saving the document.
The XLDocument is the entrypoint for clients using the RapidXLSX library..

Member Typedef Documentation

◆ XLCellChangeListener

using OpenXLSX::XLDocument::XLCellChangeListener = std::function<void(std::string_view sheetName, uint32_t row, uint16_t col, bool formulaChanged)>

Listener for cell content changes (value or formula).

Used by XLCalculationEngine to auto-dirty the dependency graph. formulaChanged is true when the formula XML was modified.

Constructor & Destructor Documentation

◆ XLDocument() [1/5]

XLDocument::XLDocument ( const IZipArchive & zipArchive = XLZipArchive())
explicit

Default constructor. Initializes an empty document package with a default ZIP archive.

Allows creating or manipulating an in-memory or custom-provided ZIP archive, decoupling the document from direct disk I/O.

◆ XLDocument() [2/5]

XLDocument::XLDocument ( std::string_view docPath,
const IZipArchive & zipArchive = XLZipArchive() )
explicit

Path-based constructor. Loads an existing document or sets the target path for a new one.

Parameters
docPathNon-owning view to the file path to minimize memory overhead during initialization.

Provides an optimized initialization path that avoids string copies when reading an existing workbook from disk.

◆ XLDocument() [3/5]

XLDocument::XLDocument ( const std::string & docPath,
const IZipArchive & zipArchive = XLZipArchive() )
explicit

Legacy string constructor. Maintained to resolve ambiguity with IZipArchive's template constructor when passing string literals or std::string.

Maintains backward compatibility for existing codebases relying on std::string, ensuring smooth upgrades.

◆ XLDocument() [4/5]

OpenXLSX::XLDocument::XLDocument ( const XLDocument & other)
delete

◆ XLDocument() [5/5]

OpenXLSX::XLDocument::XLDocument ( XLDocument && other)
defaultnoexcept

◆ ~XLDocument()

XLDocument::~XLDocument ( )

Prevents resource leaks and ensures any pending archive handles or DOM structures are properly disposed of when the object goes out of scope.

Member Function Documentation

◆ addImage() [1/2]

std::string XLDocument::addImage ( std::string_view name,
gsl::span< const uint8_t > data )
overridevirtual

◆ addImage() [2/2]

std::string XLDocument::addImage ( std::string_view name,
std::string_view data )
overridevirtual

Insert image into the archive's media folder. Uses string_view for zero-copy data transfer.

Parameters
nameFilename in the archive.
dataRaw image data as a non-owning view.
Returns
The internal package path to the image.

Injects binary image payloads into the internal media folder and registers their MIME type, laying the groundwork for visual sheet annotations.

Implements OpenXLSX::XLPackagePartFactory.

◆ addStreamedFile()

void XLDocument::addStreamedFile ( std::string_view pathInZip,
std::string_view tempFilePath )

◆ addXmlData()

XLXmlData * OpenXLSX::XLDocument::addXmlData ( XLInternalAccess ,
const std::string & path,
const std::string & id,
XLContentType type )
inline

◆ appProperties() [1/2]

XLAppProperties & OpenXLSX::XLDocument::appProperties ( )
inlinenodiscard

Access application-specific properties (metadata). [[nodiscard]] is used to prevent state-querying errors.

◆ appProperties() [2/2]

const XLAppProperties & OpenXLSX::XLDocument::appProperties ( ) const
inlinenodiscard

◆ archive() [1/2]

const IZipArchive & OpenXLSX::XLDocument::archive ( ) const
inlinenodiscardoverridevirtual

◆ archive() [2/2]

IZipArchive & OpenXLSX::XLDocument::archive ( )
inlinenodiscardoverridevirtual

Access the low-level ZIP archive for advanced package manipulation. [[nodiscard]] is used to prevent state-querying errors.

Implements OpenXLSX::XLPackageServices.

◆ cleanupSharedStrings()

void XLDocument::cleanupSharedStrings ( )

Prune unused strings from the SST and reindex referencing cells. Essential for minimizing file size and memory footprint in long-lived or large documents.

Probes the archive index for sheet relationships to conditionally access dependencies, avoiding eager and expensive XML allocations for untouched components.

◆ close()

void XLDocument::close ( )

Close the document and release underlying ZIP resources, ensuring file handles are closed properly.

Safely drops the internal DOM representations and archive handles, returning the XLDocument to a pristine, uninitialized state to prevent cross-contamination between files.

◆ compactStyles()

void XLDocument::compactStyles ( )

Compact and deduplicate all styles across the workbook and all worksheets.

◆ compressionLevel()

int XLDocument::compressionLevel ( ) const

Get the current compression level.

◆ contentTypes() [1/2]

const XLContentTypes & XLDocument::contentTypes ( ) const
nodiscardoverridevirtual

◆ contentTypes() [2/2]

XLContentTypes & XLDocument::contentTypes ( )
nodiscardoverridevirtual

Provides access to the [Content_Types].xml file, which defines the package structure and internal part mapping.

Exposes the content types manager, which is required to register new XML parts (like sheets or drawings) so Excel recognizes their purpose.

Implements OpenXLSX::XLPackageServices.

◆ coreProperties() [1/2]

XLProperties & OpenXLSX::XLDocument::coreProperties ( )
inlinenodiscard

Access core document metadata properties. [[nodiscard]] is used to prevent state-querying errors.

◆ coreProperties() [2/2]

const XLProperties & OpenXLSX::XLDocument::coreProperties ( ) const
inlinenodiscard

◆ create() [1/2]

void XLDocument::create ( const std::string & fileName)

Create a new .xlsx file with the given name. Legacy interface.

Deprecated
Use void create(std::string_view, bool) for explicit overwrite control.

Maintains backward compatibility for creating new documents using std::string, ensuring smooth upgrades.

◆ create() [2/2]

void XLDocument::create ( std::string_view fileName,
bool forceOverwrite = XLForceOverwrite )

Initialize a new .xlsx package from a built-in template.

Parameters
fileNameTarget path for the new package.
forceOverwritePrevents accidental data loss unless explicitly requested via XLForceOverwrite.

Bootstraps a minimal, valid OOXML document structure from scratch. Uses hardcoded string templates instead of a binary payload to prevent carrying opaque blobs in the executable.

◆ createChart()

XLChart XLDocument::createChart ( XLChartType type = XLChartType::Bar)
overridevirtual

◆ createDrawing()

XLDrawing XLDocument::createDrawing ( )
overridevirtual

◆ createPivotCacheDefinition()

XLPivotCacheDefinition XLDocument::createPivotCacheDefinition ( )

◆ createPivotCacheRecords()

XLPivotCacheRecords XLDocument::createPivotCacheRecords ( std::string_view cacheDefPath)

◆ createPivotSlicerCache()

std::string XLDocument::createPivotSlicerCache ( uint32_t pivotCacheId,
uint32_t sheetId,
std::string_view pivotTableName,
std::string_view name,
std::string_view sourceName )
overridevirtual

◆ createPivotTable()

XLPivotTable XLDocument::createPivotTable ( )

◆ createSlicer()

std::string XLDocument::createSlicer ( std::string_view name,
std::string_view cacheName,
std::string_view caption,
std::string_view existingSlicerFile = {} )
overridevirtual

◆ createTableSlicerCache()

std::string XLDocument::createTableSlicerCache ( uint32_t tableId,
uint32_t tableColumnId,
std::string_view name,
std::string_view sourceName )
overridevirtual

◆ customProperties()

XLCustomProperties & XLDocument::customProperties ( )

◆ defaultAuthor()

std::string XLDocument::defaultAuthor ( ) const

Get the default author for comments and notes.

◆ deleteMacro()

void XLDocument::deleteMacro ( )

Deletes the VBA macro project and all macro-related signatures/relationships from the document. This is typically used to sanitize a file before saving it as a standard .xlsx.

◆ deleteManagedXmlPart()

void XLDocument::deleteManagedXmlPart ( std::string_view path)

Remove a managed package XML part (archive entry, content type, in-memory XLXmlData).

Also removes the companion part relationships file under _rels when present. Used by pivot/slicer GC.

◆ deleteProperty()

void XLDocument::deleteProperty ( XLProperty theProperty)

Remove specific metadata property.

Clears a specific metadata property to clean up unneeded, obsolete, or sensitive document traces.

◆ deleteSlicerFileAndOrphanCache()

void XLDocument::deleteSlicerFileAndOrphanCache ( const std::string & name)
overridevirtual

◆ drawing()

XLDrawing XLDocument::drawing ( std::string_view path)
overridevirtual

◆ drawingRelationships()

XLRelationships XLDocument::drawingRelationships ( std::string_view drawingPath)
overridevirtual

Lazily resolves or bootstraps drawing-level relationships, which are required when linking images or charts within a drawing surface.

Implements OpenXLSX::XLPackageServices.

◆ emplaceXmlPart()

XLXmlData * XLDocument::emplaceXmlPart ( const std::string & path,
const std::string & id,
XLContentType type )
overridevirtual

Create and register a new managed XML part in the document's part list.

Implements OpenXLSX::XLPackageServices.

◆ execCommand()

bool XLDocument::execCommand ( const XLCommand & command)

Provides a centralized mutation interface for document-level changes. Abstracted as commands to decouple the UI/API layers from the internal DOM routing and dependency management logic.

◆ execQuery() [1/2]

XLQuery XLDocument::execQuery ( const XLQuery & query)

Non-const overload for querying document state.

◆ execQuery() [2/2]

XLQuery XLDocument::execQuery ( const XLQuery & query) const
nodiscard

Execute a state-querying operation without modifying the document. [[nodiscard]] is used to prevent state-querying errors.

Provides a centralized read interface for querying document state. Decouples consumers from traversing the relationship graphs directly.

◆ extractXmlFromArchive()

std::string XLDocument::extractXmlFromArchive ( std::string_view path)
nodiscard

Fetch raw XML content for a specific package path. Used internally for lazily loading components on demand, or for advanced testing/inspection.

Serves as the foundational bridge between the raw ZIP layer and the parsed DOM layer, safely extracting content only when explicitly requested.

◆ findOrCreatePivotSlicerCache()

std::string XLDocument::findOrCreatePivotSlicerCache ( uint32_t pivotCacheId,
uint32_t sheetId,
std::string_view pivotTableName,
std::string_view name,
std::string_view sourceName )
overridevirtual

◆ findOrCreateTableSlicerCache()

std::string XLDocument::findOrCreateTableSlicerCache ( uint32_t tableId,
uint32_t tableColumnId,
std::string_view name,
std::string_view sourceName )
overridevirtual

◆ findXmlPart() [1/2]

const XLXmlData * XLDocument::findXmlPart ( std::string_view path,
bool doNotThrow = false ) const
nodiscardoverridevirtual

◆ findXmlPart() [2/2]

XLXmlData * XLDocument::findXmlPart ( std::string_view path,
bool doNotThrow = false )
nodiscardoverridevirtual

Locate a managed XML part by package path (e.g. "xl/pivotCache/pivotCacheDefinition1.xml").

Parameters
doNotThrowWhen true, return nullptr if missing instead of throwing.

Implements OpenXLSX::XLPackageServices.

◆ getImage()

std::string XLDocument::getImage ( std::string_view path) const
nodiscardoverridevirtual

Fetch raw image data from the document archive (xl/media/).

Retrieves the raw binary payload of an embedded image, enabling external rendering or extraction of worksheet media.

Implements OpenXLSX::XLPackagePartFactory.

◆ getString()

const char * XLDocument::getString ( int32_t index) const
nodiscardoverridevirtual

Resolve an SST index to a null-terminated C string.

Note
Pointer is valid while the document / SST remains alive.

Implements OpenXLSX::XLSharedStringTable.

◆ getStringIndex()

int32_t XLDocument::getStringIndex ( std::string_view str) const
nodiscardoverridevirtual

Look up an existing string's index.

Returns
Index, or a negative value when the string is not present.

Implements OpenXLSX::XLSharedStringTable.

◆ getStringView()

std::string_view XLDocument::getStringView ( int32_t index) const
nodiscardoverridevirtual

Resolve an SST index to a string_view into the arena/cache.

Note
View is valid while the document / SST remains alive.

Implements OpenXLSX::XLSharedStringTable.

◆ getXmlData() [1/4]

XLXmlData * XLDocument::getXmlData ( std::string_view path,
bool doNotThrow = false )
nodiscardprotected

Provide access to managed XML data nodes, enabling centralized XML state management. doNotThrow allows safe querying when a component's presence is uncertain.

Returns a mutable pointer to the requested XML part, acting as the document's central DOM registry cache.

◆ getXmlData() [2/4]

const XLXmlData * XLDocument::getXmlData ( std::string_view path,
bool doNotThrow = false ) const
nodiscardprotected

Returns a read-only pointer to the requested XML part from the DOM cache.

◆ getXmlData() [3/4]

XLXmlData * OpenXLSX::XLDocument::getXmlData ( XLInternalAccess ,
std::string_view path,
bool doNotThrow = false )
inlinenodiscard

◆ getXmlData() [4/4]

const XLXmlData * OpenXLSX::XLDocument::getXmlData ( XLInternalAccess ,
std::string_view path,
bool doNotThrow = false ) const
inlinenodiscard

◆ hasMacro()

bool XLDocument::hasMacro ( ) const
nodiscard

Provides access to custom properties (metadata) that can be set for the document.

Check if the loaded document contains a VBA macro project (e.g. xl/vbaProject.bin)

Returns
true if macro project exists

Provides access to custom properties, enabling the storage of application-specific metadata within the OOXML container.

◆ hasPersons()

bool XLDocument::hasPersons ( ) const

Check if the document has a persons metadata file.

Overrides the default XML header attributes, allowing consumers to dictate XML standalone status or encoding during serialization.

◆ hasSheetComments()

bool XLDocument::hasSheetComments ( uint16_t sheetXmlNo) const
nodiscardoverridevirtual

Probes the archive index for comments to conditionally parse them, optimizing load times for sheets without annotations.

Implements OpenXLSX::XLPackagePartFactory.

◆ hasSheetDrawing()

bool XLDocument::hasSheetDrawing ( uint16_t sheetXmlNo) const
nodiscardoverridevirtual

Probes the archive index for drawings to verify the presence of visual elements before attempting to parse them.

Implements OpenXLSX::XLPackagePartFactory.

◆ hasSheetRelationships()

bool XLDocument::hasSheetRelationships ( uint16_t sheetXmlNo,
bool isChartsheet = false ) const
nodiscardoverridevirtual

Component presence checks, used to avoid unnecessary parsing of absent components in the package.

Note
Also part of XLPackagePartFactory.

Implements OpenXLSX::XLPackagePartFactory.

◆ hasSheetTables()

bool XLDocument::hasSheetTables ( uint16_t sheetXmlNo) const
nodiscardoverridevirtual

Probes the archive index for table definitions, delaying XML parsing until table data is explicitly requested.

Implements OpenXLSX::XLPackagePartFactory.

◆ hasSheetThreadedComments()

bool XLDocument::hasSheetThreadedComments ( uint16_t sheetXmlNo) const
nodiscardoverridevirtual

◆ hasSheetVmlDrawing()

bool XLDocument::hasSheetVmlDrawing ( uint16_t sheetXmlNo) const
nodiscardoverridevirtual

Probes the archive index for legacy VML drawings (often used for comments or form controls) to avoid redundant DOM creation.

Implements OpenXLSX::XLPackagePartFactory.

◆ hasXmlData()

bool XLDocument::hasXmlData ( std::string_view path) const
nodiscardprotected

Provides a safe lookup into the DOM cache to verify the existence of optional parts without triggering exceptions.

◆ isOpen()

bool XLDocument::isOpen ( ) const
nodiscard
Returns
True if the document is active and editable.

Provides an explicit boolean check for the document's readiness state, preventing operations on uninitialized archives.

◆ maxEntryUncompressedSize()

size_t OpenXLSX::XLDocument::maxEntryUncompressedSize ( ) const
inlinenodiscard

◆ mutex()

std::shared_mutex & OpenXLSX::XLDocument::mutex ( ) const
inline

Get the document-level mutex for thread-safe operations.

◆ name()

std::string XLDocument::name ( ) const
nodiscard

Access filename to uniquely identify the document in the package.

Returns
The current document's filename. [[nodiscard]] is used to prevent state-querying errors.

Provides the base filename to facilitate identification in UI, logging, or reporting contexts.

◆ nextTableId()

uint32_t XLDocument::nextTableId ( ) const
nodiscardoverridevirtual

Atomic table ID generator to ensure workbook-wide uniqueness for Excel table structures. [[nodiscard]] is used to enforce correct result consumption.

Calculates the next available auto-incrementing ID across all tables to ensure unique table references within the document, a strict OOXML requirement.

Implements OpenXLSX::XLPackagePartFactory.

◆ notifyCellChanged()

void XLDocument::notifyCellChanged ( std::string_view sheetName,
uint32_t row,
uint16_t col,
bool formulaChanged )

Notify listeners that a cell changed (value and/or formula).

Note
Called from formula/value write paths; safe to call with empty sheetName.

◆ open() [1/2]

void XLDocument::open ( std::string_view fileName)

Open an existing .xlsx package. Uses std::string_view for zero-copy path processing.

Parameters
fileNamePath to the file to open.

◆ open() [2/2]

void XLDocument::open ( std::string_view fileName,
const std::string & password )

Open an existing encrypted .xlsx package.

Parameters
fileNamePath to the file to open.
passwordThe user password for decryption.

Establishes the document's internal structure by parsing its root relationships and mandatory XML parts. This serves as the primary entry point for accessing and mutating any existing workbook.

◆ operator bool()

XLDocument::operator bool ( ) const
explicitnodiscard
Returns
True if the document archive is valid and properly loaded.

Allows fast truthy checks to verify if the underlying zip archive is successfully bound and accessible.

◆ operator=() [1/2]

XLDocument & OpenXLSX::XLDocument::operator= ( const XLDocument & other)
delete

◆ operator=() [2/2]

XLDocument & OpenXLSX::XLDocument::operator= ( XLDocument && other)
defaultnoexcept

◆ path()

const std::string & XLDocument::path ( ) const
nodiscard

Access the full filesystem path of the current document. [[nodiscard]] prevents ignoring the current path reference.

Returns the active file path to allow consumers to verify or display the target destination.

◆ persons()

XLPersons & XLDocument::persons ( )

Access the persons metadata for threaded comments.

◆ property()

std::string XLDocument::property ( XLProperty prop) const
nodiscard

Fetch metadata property by type (e.g., Title, Creator).

Provides read access to standard OOXML document metadata (core and extended properties) such as creator, application version, or creation date.

◆ registerCellChangeListener()

void XLDocument::registerCellChangeListener ( const void * token,
XLCellChangeListener listener )

Register a cell-change listener. token must be unique (e.g. this of the engine).

◆ save()

void XLDocument::save ( )

Save changes to the original file path.

Commits the current DOM state to the archive, updating dimensions and calculation chains before disk flush to ensure Excel interprets the modified file as valid.

◆ saveAs() [1/3]

void XLDocument::saveAs ( const std::string & fileName)

Save the document with a new name. Legacy interface.

Deprecated
Use void saveAs(std::string_view, bool) for explicit overwrite control.

Maintains backward compatibility for saving documents using std::string, ensuring smooth upgrades.

◆ saveAs() [2/3]

void XLDocument::saveAs ( std::string_view fileName,
bool forceOverwrite = XLForceOverwrite )

Persistence to a new location.

Parameters
fileNameTarget path.
forceOverwriteProtects existing files from being overwritten without explicit intent.

◆ saveAs() [3/3]

void XLDocument::saveAs ( std::string_view fileName,
const std::string & password,
bool forceOverwrite = XLForceOverwrite )

Persistence to a new location with encryption.

Parameters
fileNameTarget path.
passwordPassword for encryption.
forceOverwriteProtects existing files from being overwritten.

Serializes the modified DOM objects into their respective XML strings and constructs a new ZIP archive. Caches and restores unhandled media/VBA entries to prevent data loss in macro-enabled files.

◆ setCompressionLevel()

void XLDocument::setCompressionLevel ( int level)

Set the compression level for packing the document.

Parameters
levelCompression level (1-9). Default is 1.

◆ setDefaultAuthor()

void XLDocument::setDefaultAuthor ( const std::string & author)

Set the default author for comments and notes.

◆ setFormulaNeedsRecalculation()

void OpenXLSX::XLDocument::setFormulaNeedsRecalculation ( bool status = true)
inline

Marks the document to require formula recalculation on load.

◆ setMaxEntryUncompressedSize()

void OpenXLSX::XLDocument::setMaxEntryUncompressedSize ( size_t maxBytes)
inline

Cap uncompressed size for archive.getEntry() loads (0 = unlimited).

Zip-bomb / OOM guard applied when bulk-loading XML parts into memory. Call after open() or create(); default is unlimited for compatibility.

◆ setProperty()

void XLDocument::setProperty ( XLProperty prop,
std::string_view value )

Update metadata property. Uses string_view to allow updating from literals without temporary allocations.

Parameters
propThe property to set.
valueA non-owning view to the value string.

Mutates document metadata, explicitly validating format-specific constraints (e.g., boolean strings or version formatting 'XX.XXXX') to prevent schema validation failures in Excel.

◆ setSavingDeclaration()

void XLDocument::setSavingDeclaration ( XLXmlSavingDeclaration const & savingDeclaration)

◆ sharedFormulas()

std::map< void *, std::unordered_map< uint32_t, SharedFormula > > & OpenXLSX::XLDocument::sharedFormulas ( XLInternalAccess ) const
inline

◆ sharedStrings()

const XLSharedStrings & OpenXLSX::XLDocument::sharedStrings ( ) const
inlinenodiscard

Access the workbook's central Shared String Table (SST). The SST reduces file size by deduplicating text across the entire package.

Note
Full SST (including getOrCreate / append). Prefer sharedStringTable() for read-only lookups.

◆ sharedStringTable()

const XLSharedStringTable & OpenXLSX::XLDocument::sharedStringTable ( ) const
inlinenodiscard

Read-only SST port (index ↔ string lookups only).

Also available as XLSharedStringTable via inheritance; this alias documents intent.

◆ sheetComments()

XLComments XLDocument::sheetComments ( uint16_t sheetXmlNo)
overridevirtual

Bootstraps or retrieves the comment thread storage for a sheet, required to read or write cell-anchored notes.

Implements OpenXLSX::XLPackagePartFactory.

◆ sheetDrawing()

XLDrawing XLDocument::sheetDrawing ( uint16_t sheetXmlNo)
overridevirtual

Initializes or retrieves the drawing canvas for a sheet, serving as the root container for images, charts, and shapes.

Implements OpenXLSX::XLPackagePartFactory.

◆ sheetRelationships()

XLRelationships XLDocument::sheetRelationships ( uint16_t sheetXmlNo,
bool isChartsheet = false )
overridevirtual

Lazily resolves or bootstraps sheet-level relationships. This is necessary to construct valid linkages before adding interactive or visual elements to a sheet.

Implements OpenXLSX::XLPackagePartFactory.

◆ sheetTables()

XLTableCollection XLDocument::sheetTables ( uint16_t sheetXmlNo)
overridevirtual

◆ sheetThreadedComments()

XLThreadedComments XLDocument::sheetThreadedComments ( uint16_t sheetXmlNo)
overridevirtual

Bootstraps or retrieves the table registry for a sheet, facilitating structured data manipulation and formatting.

Implements OpenXLSX::XLPackagePartFactory.

◆ sheetVmlDrawing()

XLVmlDrawing XLDocument::sheetVmlDrawing ( uint16_t sheetXmlNo)
overridevirtual

Initializes or retrieves the legacy VML drawing canvas, primarily required for anchoring cell comments to the UI.

Implements OpenXLSX::XLPackagePartFactory.

◆ showWarnings()

void XLDocument::showWarnings ( )

Enables stdout logging for non-critical schema deviations (e.g., unknown xml relationships), which is vital for debugging compatibility issues.

◆ stringCount()

int32_t XLDocument::stringCount ( ) const
nodiscardoverridevirtual
Returns
Number of entries currently in the SST cache.

Implements OpenXLSX::XLSharedStringTable.

◆ stringExists()

bool XLDocument::stringExists ( std::string_view str) const
nodiscardoverridevirtual
Returns
true if str is already registered in the SST.

Implements OpenXLSX::XLSharedStringTable.

◆ styles() [1/2]

XLStyles & XLDocument::styles ( )
nodiscard

Provides access to shared document styles (fonts, fills, borders, cell formats).

Provides access to the global stylesheet manager to retrieve or define fonts, fills, borders, and number formats used across the workbook.

◆ styles() [2/2]

const XLStyles & XLDocument::styles ( ) const
nodiscard

◆ suppressWarnings()

void XLDocument::suppressWarnings ( )

Silences non-critical schema deviation warnings to keep the console output clean during production use.

◆ unregisterCellChangeListener()

void XLDocument::unregisterCellChangeListener ( const void * token)

Remove a previously registered listener.

◆ validatePackageInvariants()

void XLDocument::validatePackageInvariants ( ) const

Validate package-level OOXML invariants before serialization.

Checks workbook presence, Content_Types overrides for managed parts, and sheet relationship targets. Invoked automatically from saveAs(); may also be called by tests. Throws XLException on hard failures.

Hard checks that catch structural corruption before ZIP commit.

◆ validateSheetName()

bool XLDocument::validateSheetName ( std::string_view sheetName,
bool throwOnInvalid = false )

Ensure worksheet names adhere to Excel's naming rules.

Worksheet names cannot: Be blank. Contain more than 31 characters. Contain any of the following characters: / \ ? * : [ ] For example, 02/17/2016 would not be a valid worksheet name, but 02-17-2016 would work fine. Begin or end with an apostrophe ('), but they can be used in between text or numbers in a name. Be named "History". This is a reserved word Excel uses internally.

Worksheet names must adhere to strict Excel naming rules to ensure compatibility across different spreadsheet applications and prevent OOXML schema violations. Key restrictions include length (31 chars), forbidden characters (/ \ ? * : [ ]), and the reserved name "History".

◆ workbook()

XLWorkbook XLDocument::workbook ( ) const
nodiscard

Get the underlying workbook object, containing worksheets and global data state. [[nodiscard]] prevents side-effect-free querying errors.

Provides access to the core workbook component, serving as the gateway to manage worksheets, chartsheets, and global definitions.

◆ workbookRelationships()

XLRelationships & OpenXLSX::XLDocument::workbookRelationships ( )
inlineoverridevirtual

Get workbook relationships.

Implements OpenXLSX::XLPackageServices.

◆ xmlRelationships()

XLRelationships XLDocument::xmlRelationships ( std::string_view xmlPath)
overridevirtual

Get relationships for an arbitrary XML file (e.g. pivot tables).

Shared String Table (SST) cleanup. Rationale: Over time, the SST can accumulate unused strings as cells are modified or deleted. This method performs a full workbook traversal to identify strings currently in use, remaps their indices to a new, compact table, and moves the string data to avoid copies. Index 0 is reserved for empty strings by convention.

Implements OpenXLSX::XLPackageServices.


The documentation for this class was generated from the following files: