OfficeIMO

API Reference

Class

ExcelDocument

Namespace OfficeIMO.Excel
Assembly OfficeIMO.Excel
Implements
IDisposable IAsyncDisposable
Attributes
DefaultMember("Item")

Represents an Excel document and provides methods for creating, loading and saving spreadsheets.

Inheritance

  • Object
  • ExcelDocument

Constructors

Methods

public Void AddBackLinksToToc(String tocSheetName = "TOC", Int32 row = 2, Int32 col = 1, String text = "← TOC") #
Returns: Void

Adds a small back link to the TOC on each worksheet at the given cell (default A2).

Parameters

tocSheetName System.String = "TOC" optionalposition: 0
row System.Int32 = 2 optionalposition: 1
col System.Int32 = 1 optionalposition: 2
text System.String = "← TOC" optionalposition: 3
public Void AddTableOfContents(String sheetName = "TOC", Boolean placeFirst = true, Boolean withHyperlinks = true, Boolean includeNamedRanges = false, Boolean includeHiddenNamedRanges = false, Predicate<String> rangeNameFilter = null, Boolean styled = true) #
Returns: Void

Adds or refreshes a visually styled Table of Contents sheet with hyperlinks.

Parameters

sheetName System.String = "TOC" optionalposition: 0
TOC sheet name.
placeFirst System.Boolean = true optionalposition: 1
Move TOC as the first sheet.
withHyperlinks System.Boolean = true optionalposition: 2
Create internal hyperlinks.
includeNamedRanges System.Boolean = false optionalposition: 3
Also list defined names in a dedicated column.
includeHiddenNamedRanges System.Boolean = false optionalposition: 4
When listing defined names, include ones marked Hidden.
rangeNameFilter System.Predicate{System.String} = null optionalposition: 5
Optional filter to include only matching defined names.
styled System.Boolean = true optionalposition: 6
When true, renders a banner and a formatted table with AutoFilter.
AddWorkSheet 2 overloads
public ExcelSheet AddWorkSheet(String workSheetName = "") #
Returns: ExcelSheet

Adds a worksheet to the document.

Parameters

workSheetName System.String = "" optionalposition: 0
Worksheet name.

Returns

Created ExcelSheet instance.

public ExcelSheet AddWorkSheet(String workSheetName, SheetNameValidationMode validationMode) #
Returns: ExcelSheet

Adds a worksheet to the document with control over name validation.

Parameters

workSheetName System.String requiredposition: 0
Requested worksheet name.
validationMode OfficeIMO.Excel.SheetNameValidationMode requiredposition: 1
How to validate the sheet name: None (no checks), Sanitize (coerce), or Strict (throw on invalid).

Returns

Created ExcelSheet instance.

public ExcelFluentWorkbook AsFluent() #
Returns: ExcelFluentWorkbook

Returns a fluent API wrapper for this document.

public Void Close() #
Returns: Void

Closes the underlying spreadsheet document.

public Void Compose(String sheetName, Action<SheetComposer> compose, SheetTheme theme = null) #
Returns: Void

Fluent sugar: compose a worksheet using SheetComposer without exposing the builder type to callers.

Parameters

sheetName System.String requiredposition: 0
compose System.Action{OfficeIMO.Excel.Fluent.SheetComposer} requiredposition: 1
theme OfficeIMO.Excel.Fluent.SheetTheme = null optionalposition: 2
Create 4 overloads
public static ExcelDocument Create(String filePath) #
Returns: ExcelDocument

Creates a new Excel document at the specified path.

Parameters

filePath System.String requiredposition: 0
Path to the new file.

Returns

Created ExcelDocument instance.

public static ExcelDocument Create(Stream stream, Boolean autoSave = true) #
Returns: ExcelDocument

Creates a new Excel document at the specified path with explicit AutoSave behavior.

Parameters

filePath System.String requiredposition: 0
Path to the new file.
autoSave System.Boolean = true optionalposition: 1
When true, saves changes on dispose.

Returns

Created ExcelDocument instance.

Create(System.IO.Stream stream, System.Boolean autoSave) #

Creates a new Excel document in memory and optionally persists it to the provided stream on dispose.

Parameters

stream System.IO.Stream required
Destination stream to receive the workbook package.
autoSave System.Boolean required
When true, the package is written back to the stream on dispose.

Returns

Created ExcelDocument instance.

public static ExcelDocument Create(String filePath, String workSheetName) #
Returns: ExcelDocument

Creates a new Excel document with a single worksheet.

Parameters

filePath System.String requiredposition: 0
Path to the new file.
workSheetName System.String requiredposition: 1
Name of the worksheet.

Returns

Created ExcelDocument instance.

public ExcelWorkbookSnapshot CreateInspectionSnapshot(ExcelReadOptions options = null) #
Returns: ExcelWorkbookSnapshot

Creates an immutable workbook snapshot that exposes OfficeIMO's current workbook model for downstream integrations.

Parameters

options OfficeIMO.Excel.ExcelReadOptions = null optionalposition: 0
public ExcelDocumentReader CreateReader(ExcelReadOptions options = null) #
Returns: ExcelDocumentReader

Creates a reader that shares this document's underlying OpenXML handle (no new file handle). Caller should dispose the reader after use; it will not close this document.

Parameters

options OfficeIMO.Excel.ExcelReadOptions = null optionalposition: 0
public Void CreateTableOfContents(String sheetName = "TOC") #
Returns: Void

Backward-compatible alias for AddTableOfContents.

Parameters

sheetName System.String = "TOC" optionalposition: 0
public virtual Void Dispose() #
Returns: Void

Releases resources used by the document.

public virtual async ValueTask DisposeAsync() #
Returns: ValueTask

Asynchronously releases resources used by the document.

EnsureValidDefinedName(System.String arg1, OfficeIMO.Excel.NameValidationMode arg2) #

Ensures a defined name complies with Excel rules. In Sanitize mode, returns a corrected name. Throws in Strict mode when input is invalid. Rules: - 1..255 characters - First char must be a letter or underscore - Allowed characters: letters, digits, underscore, period - Cannot look like a cell reference (e.g., A1, AA10) or an R1C1 reference - Cannot be TRUE or FALSE (case-insensitive)

Parameters

arg1 System.String required
arg2 OfficeIMO.Excel.NameValidationMode required
public IReadOnlyDictionary<String, String> GetAllNamedRanges(ExcelSheet scope = null) #
Returns: IReadOnlyDictionary<String, String>

Returns all defined names with their A1 ranges, optionally limited to a sheet scope.

Parameters

scope OfficeIMO.Excel.ExcelSheet = null optionalposition: 0
public String GetNamedRange(String name, ExcelSheet scope = null) #
Returns: String

Returns the A1 range for a defined name. If scope is supplied, searches a sheet‑local name first.

Parameters

name System.String requiredposition: 0
Defined name to resolve.
scope OfficeIMO.Excel.ExcelSheet = null optionalposition: 1
Optional sheet scope to resolve a local name.

Returns

A1 range string or null if not found.

GetOrInitTableNameCache() #

Returns the workbook-level cache of table names, initializing it from the current document if needed. Case-insensitive comparison.

public IReadOnlyList<ExcelPivotTableInfo> GetPivotTables() #
Returns: IReadOnlyList<ExcelPivotTableInfo>

Returns all pivot tables defined in the workbook.

public ExcelSheet GetSheet(String name) #
Returns: ExcelSheet

Gets a worksheet by name.

Parameters

name System.String requiredposition: 0
public IReadOnlyList<String> GetSheetNames() #
Returns: IReadOnlyList<String>

Returns worksheet names in workbook order.

public IReadOnlyList<ExcelTableInfo> GetTables() #
Returns: IReadOnlyList<ExcelTableInfo>

Returns all Excel tables defined in the workbook.

Load 2 overloads
public static ExcelDocument Load(String filePath, Boolean readOnly = false, Boolean autoSave = false, Action<String, Exception> log = null, OpenSettings openSettings = null) #
Returns: ExcelDocument

Loads an existing Excel document.

Parameters

filePath System.String requiredposition: 0
Path to the file.
readOnly System.Boolean = false optionalposition: 1
Open the file in read-only mode.
autoSave System.Boolean = false optionalposition: 2
Enable auto-save on dispose.
log System.Action{System.String,System.Exception} = null optionalposition: 3
Optional callback invoked when normalization failures are encountered.
openSettings DocumentFormat.OpenXml.Packaging.OpenSettings = null optionalposition: 4
Optional Open XML settings to control how the package is opened.

Returns

Loaded ExcelDocument instance.

public static ExcelDocument Load(Stream stream, Boolean readOnly = false, Boolean autoSave = false, OpenSettings openSettings = null) #
Returns: ExcelDocument

Loads an existing Excel document from the provided stream.

Parameters

stream System.IO.Stream requiredposition: 0
Input stream containing the workbook package.
readOnly System.Boolean = false optionalposition: 1
Open the document in read-only mode.
autoSave System.Boolean = false optionalposition: 2
Enable auto-save on dispose.
openSettings DocumentFormat.OpenXml.Packaging.OpenSettings = null optionalposition: 3
Optional Open XML settings to control how the package is opened.

Returns

Loaded ExcelDocument instance.

LoadAsync 2 overloads
public static async Task<ExcelDocument> LoadAsync(String filePath, Boolean readOnly = false, Boolean autoSave = false, OpenSettings openSettings = null) #
Returns: Task<ExcelDocument>

Asynchronously loads an Excel document from the specified path.

Parameters

filePath System.String requiredposition: 0
Path to the Excel file.
readOnly System.Boolean = false optionalposition: 1
Open the file in read-only mode.
autoSave System.Boolean = false optionalposition: 2
Enable auto-save on dispose.
openSettings DocumentFormat.OpenXml.Packaging.OpenSettings = null optionalposition: 3
Optional Open XML settings to control how the package is opened.

Returns

Loaded ExcelDocument instance.

Exceptions

  • FileNotFoundException – Thrown when the file does not exist.
public static async Task<ExcelDocument> LoadAsync(Stream stream, Boolean readOnly = false, Boolean autoSave = false, OpenSettings openSettings = null, CancellationToken cancellationToken = null) #
Returns: Task<ExcelDocument>

Asynchronously loads an Excel document from the provided stream.

Parameters

stream System.IO.Stream requiredposition: 0
Input stream containing the workbook package.
readOnly System.Boolean = false optionalposition: 1
Open the document in read-only mode.
autoSave System.Boolean = false optionalposition: 2
Enable auto-save on dispose.
openSettings DocumentFormat.OpenXml.Packaging.OpenSettings = null optionalposition: 3
Optional Open XML settings to control how the package is opened.
cancellationToken System.Threading.CancellationToken = null optionalposition: 4
Cancellation token.

Returns

Loaded ExcelDocument instance.

NormalizeRange(System.String arg1) #

Normalizes an A1-style range, ensuring absolute references and validating format. Accepts an optional sheet prefix (e.g. ''Sheet1'!A1:B2'). Throws ArgumentException if the input is not a valid A1 range or cell reference.

Parameters

arg1 System.String required
public Void Open(String filePath = "", Boolean openExcel = true) #
Returns: Void

Opens the document with the associated application.

Parameters

filePath System.String = "" optionalposition: 0
Optional path to open.
openExcel System.Boolean = true optionalposition: 1
Whether to launch Excel.
public Void PreflightWorkbook() #
Returns: Void

Performs a safety preflight across all worksheets to reduce the likelihood of Excel prompting for repairs on open. It removes empty containers (Hyperlinks/MergeCells), drops orphaned drawing and header/footer references, and cleans up invalid table references.

public ExcelFluentReadWorkbook Read(ExcelReadOptions options = null) #
Returns: ExcelFluentReadWorkbook

Starts a fluent read pipeline over this open document.

Parameters

options OfficeIMO.Excel.ExcelReadOptions = null optionalposition: 0
public Boolean RemoveNamedRange(String name, ExcelSheet scope = null, Boolean save = true) #
Returns: Boolean

Removes a defined name. If scope is provided, removes the sheet‑local name; otherwise the global name.

Parameters

name System.String requiredposition: 0
Defined name to remove.
scope OfficeIMO.Excel.ExcelSheet = null optionalposition: 1
Optional sheet scope.
save System.Boolean = true optionalposition: 2
When true, saves the workbook after removal.

Returns

True if the name existed and was removed; otherwise false.

RemoveReservedTableName(System.String arg1) #

Removes the given table name from the cache. Intended for future table deletion APIs. Safe to call even if the cache hasn't been initialized.

Parameters

arg1 System.String required
public Void RemoveWorkSheet(String sheetName) #
Returns: Void

Removes a worksheet by name, deleting its part and entry in the workbook.

Parameters

sheetName System.String requiredposition: 0
RepairDefinedNames(System.Boolean arg1) #

Repairs common issues with defined names that can trigger Excel's file repair, such as duplicates within the same scope, invalid LocalSheetId after sheet reordering/removal, or references containing #REF!.

Parameters

arg1 System.Boolean required
ReserveTableName(System.String arg1) #

Adds the given table name to the cache. Should be called once the name is finalized.

Parameters

arg1 System.String required
public Void SafeSave(String filePath = "", Boolean openExcel = false, Boolean writeReportOnIssues = true) #
Returns: Void

Saves the document and writes an optional OpenXML validation report (sidecar file) next to the saved .xlsx when issues are detected. Useful to diagnose any remaining problems that could cause Excel's repair dialog.

Parameters

filePath System.String = "" optionalposition: 0
Destination path. Empty uses FilePath.
openExcel System.Boolean = false optionalposition: 1
When true, launches the saved file.
writeReportOnIssues System.Boolean = true optionalposition: 2
When true (default), writes .xlsx.validation.txt on issues.
Save 6 overloads
public Void Save(Stream destination, ExcelSaveOptions options) #
Returns: Void

Saves the document and optionally opens it.

Parameters

filePath System.String requiredposition: 0
Path to save to.
openExcel System.Boolean requiredposition: 1
Whether to open the file after saving.
public Void Save(String filePath, Boolean openExcel, ExcelSaveOptions options) #
Returns: Void

Saves the document with optional robustness options.

Parameters

filePath System.String requiredposition: 0
Destination path. When empty, uses the original FilePath.
openExcel System.Boolean requiredposition: 1
When true, opens the saved file in the system's associated app.
options OfficeIMO.Excel.ExcelSaveOptions requiredposition: 2
Optional save behaviors (safe defined-name repair, post-save Open XML validation).
public Void Save() #
Returns: Void

Saves the document without opening it.

public Void Save(Stream destination) #
Returns: Void

Saves the document and optionally opens it.

Parameters

openExcel System.Boolean requiredposition: 0
Whether to open the file after saving.
Save(System.IO.Stream destination) #

Saves the document into a writable stream.

Parameters

destination System.IO.Stream required
Writable stream that receives the Excel package content.
Save(System.IO.Stream destination, OfficeIMO.Excel.ExcelSaveOptions options) #

Saves the document into a writable stream with optional robustness options.

Parameters

destination System.IO.Stream required
Writable stream that receives the Excel package content.
options OfficeIMO.Excel.ExcelSaveOptions required
Optional save behaviors (safe defined-name repair, post-save Open XML validation).
SaveAsync 6 overloads
public async Task SaveAsync(Stream destination, ExcelSaveOptions options, CancellationToken cancellationToken = null) #
Returns: Task

Asynchronously saves the document.

Parameters

filePath System.String requiredposition: 0
Optional path to save to.
openExcel System.Boolean requiredposition: 1
Whether to open Excel after saving.
cancellationToken System.Threading.CancellationToken = null optionalposition: 2
Cancellation token.

Returns

A task representing the asynchronous operation.

public async Task SaveAsync(String filePath, Boolean openExcel, ExcelSaveOptions options, CancellationToken cancellationToken = null) #
Returns: Task

Asynchronously saves the document with optional robustness options.

Parameters

filePath System.String requiredposition: 0
Destination path. When empty, uses the original FilePath.
openExcel System.Boolean requiredposition: 1
When true, opens the saved file in the system's associated app.
options OfficeIMO.Excel.ExcelSaveOptions requiredposition: 2
Optional save behaviors (safe defined-name repair, post-save Open XML validation).
cancellationToken System.Threading.CancellationToken = null optionalposition: 3
Cancels the asynchronous save work.
public Task SaveAsync(Boolean openExcel, CancellationToken cancellationToken = null) #
Returns: Task

Asynchronously saves the document into a writable stream.

Parameters

destination System.IO.Stream requiredposition: 0
Writable stream that receives the Excel package content.
cancellationToken System.Threading.CancellationToken = null optionalposition: 1
Cancels the asynchronous save work.
SaveAsync(System.IO.Stream destination, OfficeIMO.Excel.ExcelSaveOptions options, System.Threading.CancellationToken cancellationToken) #

Asynchronously saves the document into a writable stream with optional robustness options.

Parameters

destination System.IO.Stream required
Writable stream that receives the Excel package content.
options OfficeIMO.Excel.ExcelSaveOptions required
Optional save behaviors (safe defined-name repair, post-save Open XML validation).
cancellationToken System.Threading.CancellationToken required
Cancels the asynchronous save work.
public Task SaveAsync(CancellationToken cancellationToken = null) #
Returns: Task

Asynchronously saves the document.

Parameters

cancellationToken System.Threading.CancellationToken = null optionalposition: 0
Cancellation token.
SaveAsync(System.Boolean openExcel, System.Threading.CancellationToken cancellationToken) #

Asynchronously saves the document and optionally opens Excel.

Parameters

openExcel System.Boolean required
Whether to open Excel after saving.
cancellationToken System.Threading.CancellationToken required
Cancellation token.
public Void SetNamedRange(String name, String range, ExcelSheet scope = null, Boolean save = true, Boolean hidden = false, NameValidationMode validationMode = Sanitize) #
Returns: Void

Creates or updates a defined name pointing to an A1 range. When scope is provided, the name is local to that sheet; otherwise it is workbook‑global.

Parameters

name System.String requiredposition: 0
Defined name to create or update.
range System.String requiredposition: 1
A1 range (e.g. "A1:B10"). Can include a sheet prefix.
scope OfficeIMO.Excel.ExcelSheet = null optionalposition: 2
Optional sheet scope for a local name.
save System.Boolean = true optionalposition: 3
When true, saves the workbook after the change.
hidden System.Boolean = false optionalposition: 4
When true, marks the defined name as hidden.
validationMode OfficeIMO.Excel.NameValidationMode = Sanitize optionalposition: 5
Controls how the name and range are validated: Sanitize (default) clamps/adjusts; Strict throws on invalid input.
public Void SetPrintArea(ExcelSheet sheet, String range, Boolean save = true) #
Returns: Void

Sets the print area for a given sheet by creating a sheet-local defined name _xlnm.Print_Area.

Parameters

sheet OfficeIMO.Excel.ExcelSheet requiredposition: 0
range System.String requiredposition: 1
save System.Boolean = true optionalposition: 2
public Void SetPrintTitles(ExcelSheet sheet, Nullable<Int32> firstRow, Nullable<Int32> lastRow, Nullable<Int32> firstCol, Nullable<Int32> lastCol, Boolean save = true) #
Returns: Void

Sets rows/columns to repeat at top/left when printing a specific sheet by creating a sheet-local defined name _xlnm.Print_Titles. Pass nulls to clear existing print titles.

Parameters

sheet OfficeIMO.Excel.ExcelSheet requiredposition: 0
Target sheet.
firstRow System.Nullable{System.Int32} requiredposition: 1
First row to repeat (1-based), or null.
lastRow System.Nullable{System.Int32} requiredposition: 2
Last row to repeat (1-based), or null.
firstCol System.Nullable{System.Int32} requiredposition: 3
First column to repeat (1-based), or null.
lastCol System.Nullable{System.Int32} requiredposition: 4
Last column to repeat (1-based), or null.
save System.Boolean = true optionalposition: 5
Whether to save the workbook after the change.
public Boolean TryGetSheet(String name, out ExcelSheet sheet) #
Returns: Boolean

Tries to get a worksheet by name.

Parameters

name System.String requiredposition: 0
sheet OfficeIMO.Excel.ExcelSheet@ requiredposition: 1
public List<ValidationErrorInfo> ValidateDocument(FileFormatVersions fileFormatVersions = Microsoft365) #
Returns: List<ValidationErrorInfo>

Validates the document using the specified file format version.

Parameters

fileFormatVersions DocumentFormat.OpenXml.FileFormatVersions = Microsoft365 optionalposition: 0
File format version to validate against.

Returns

List of validation errors.

public IReadOnlyList<String> ValidateOpenXml() #
Returns: IReadOnlyList<String>

Validates the current spreadsheet with Open XML validator and returns error messages (if any). Useful for troubleshooting "Repaired Records" issues in Excel.

Properties

public Boolean SheetCachingEnabled { get; set; } #

Enables caching of ExcelSheet wrappers for faster repeat access at the cost of higher memory usage. Set to false to avoid holding references to every sheet in very large workbooks.

public IEqualityComparer<String> TableNameComparer { get; set; } #

Controls how workbook-level table name uniqueness is compared. Defaults to OrdinalIgnoreCase. Changing this will reset the internal cache and rebuild it on next use. Set it once before adding tables for predictable behavior.

public ExcelChartStylePreset DefaultChartStylePreset { get; set; } #

Optional default chart style preset applied to charts created in this workbook.

public ExecutionPolicy Execution { get; } #

Execution policy for controlling parallel vs sequential operations.

public Func<DateTimeOffset, DateTime> DateTimeOffsetWriteStrategy { get; set; } #

Controls how DateTimeOffset values are converted to DateTime before being written to worksheet cells. Defaults to LocalDateTime.

public List<ExcelSheet> Sheets { get; } #

Gets a list of worksheets contained in the document.

public FileAccess FileOpenAccess { get; } #

FileOpenAccess of the document

public Boolean DocumentIsValid { get; } #

Indicates whether the document is valid.

public List<ValidationErrorInfo> DocumentValidationErrors { get; } #

Gets the list of validation errors for the document.

public ExcelSheet Item { get; } #

Gets a worksheet by name (case-insensitive).

Item #

Gets a worksheet by 0-based index in workbook order.

Fields

public SpreadsheetDocument _spreadSheetDocument #

Underlying Open XML spreadsheet document instance.

public String FilePath #

Path to the file backing this document.

public BuiltinDocumentProperties BuiltinDocumentProperties #

Built-in (core) document properties (Title, Creator, etc.).

public ApplicationProperties ApplicationProperties #

Extended (application) properties (Company, Manager, etc.).

Extension Methods

public static ExcelSheet GetOrCreateSheet(ExcelDocument document, String name, SheetNameValidationMode validationMode) #
Returns: ExcelSheet

Returns the named sheet if it exists, otherwise creates it; falls back to the last sheet.

Parameters

document OfficeIMO.Excel.ExcelDocument requiredposition: 0
name System.String requiredposition: 1
validationMode OfficeIMO.Excel.SheetNameValidationMode requiredposition: 2