Skip to content

About

Access and edit Excel files with common interface for several Excel engines

Resources

Stars

1 star

Watchers

2 watching

Forks

Latest commit

 

History

649 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CompuMaster.Excel

A bunch of libraries to access and edit Excel files with common interface for several Excel engines

Why this project?

Worksheet preview for Avalonia

Embed a read-only XLSX worksheet view in an Avalonia app with the worksheet preview control. CompuMaster XLSX uses the control in a standalone editor that can open, edit, and save workbooks. The same bounded Open XML viewport API can be used from .NET Framework 4.8, as the Windows Forms sample demonstrates.

One common API for several Excel engines

  • CompuMaster.Excel.ExcelOps

    • Provides the common API for all following Excel engines
    • Sometimes there is the need to switch the Excel engine under the hood, because the standard MS Excel engine (via COM interop) is too slow for many operations.
    • Depending on your custom project or developer license, you might want/require to use a specific alternative Excel engine
    • Allow parallel use of several Excel engines in your project
      • at least for some work items, you need Excel engine A, while for some other work item you need Excel engine B because of its feature set, bugs, etc.
      • allow step-by-step-migrations instead of one big migration task
  • CompuMaster.Excel.MicrosoftExcel

    • Use Microsoft.Office.Interop.Excel v15 (MS Office 2013) or higher, for solutions targetting .NET Framework 4.8 or .NET 6 or higher
  • CompuMaster.Excel.EpplusFreeFixCalcsEdition

    • Based on EPPlus 4.5.3.3 with LGPL license for solutions targeting .NET Framework 4.8, .NET Standard 2.0, .NET 6, or .NET 8 and higher
  • CompuMaster.Excel.EpplusPolyformEdition

    • Use latest Epplus with Epplus Software's polyform license for solutions targetting .NET Framework 4.8 or .NET 6 or higher
  • CompuMaster.Excel.FreeSpireXls

    • Use FreeSpire.Xls for solutions targetting .NET Framework 4.8 or .NET 6 or higher
  • CompuMaster.Excel.ClosedXml

    • Read, edit, and export Excel workbooks through ExcelOps using ClosedXML. See the engine guide for supported operations and limitations.
  • CompuMaster.Excel.OpenXml

    • Automate Excel workbooks on Windows, Linux and macOS without installing Microsoft Excel. Edit templates, recalculate formulas, update references and export worksheets and charts. See the engine guide and the Excel compatibility guide for supported operations, differences and examples.

Quick & dirty engine comparison / why you shouldn't use MS Excel for all situations

In following a simplified comparison without any warranties. Subjects might change over time, too. Please contact the responsible manufacturerer especially for licensing issues.

Engine Pros Cons Note on licensing or support Manufacturer website
Microsoft Excel + 100% compatibility to Micrsoft Excel ;-) - Speed
- Dependency to windows platform only (and maybe MacOS)
* licensing per user (!)
* NOT recommended/supported for software deployment, for servers or for similar automation 1)
www.microsoft.com
Epplus 5 or higher + Speed - no export of chart images
- calculation issue when re-opening in MS Excel 2)
- limited VBA/macro support
* Polyform license
* limited community licensing
* commercial licensing available
www.epplussoftware.com
EPPlus 4 (upstream) + Speed - no export of chart images
- some (seldom-used) calculation functions not implemented
- calculation issue when re-opening in MS Excel 2)
- limited VBA/macro support
- missing support for parallelization
- limited Linux/MacOS support (because of references to System.Drawing/libgdiplus)
* LGPL; end of life, without manufacturer support
* Suitable for generating files in a trusted environment; avoid parsing untrusted XLSX files because legacy ZIP/XML handling may permit resource-exhaustion (DoS).
www.github.com/JanKallman/EPPlus
CompuMaster.EPPlus4 / Free FixCalcs + Speed
+ calculation-cache workaround 2)
- inherits many EPPlus 4 feature and platform limitations * LGPL; maintained fork of an end-of-life codebase
* Configurable ZIP, XML, and encrypted-input limits mitigate resource-exhaustion but do not make arbitrary hostile XLSX files safe to parse. Prefer a supported reader or isolate processing of externally supplied files; see the FixCalcs security guidance.
www.github.com/CompuMasterGmbH/CompuMaster.Excel
Spire.Xls + Speed
+ Charts export (windows platform only)
- calculation issue when re-opening in MS Excel 2)
- limited VBA/macro support
* commercial licensing available www.e-iceblue.com
FreeSpire.Xls + Speed
+ Charts export (windows platform only)
- Limitations by manufacturer due to free edition
- calculation issue when re-opening in MS Excel 2)
- limited VBA/macro support
* "free license"
* no official support by manufacturer
www.e-iceblue.com
CompuMaster.Excel.OpenXml + Headless Excel workbook automation on Windows, Linux and macOS
+ Broad Excel formula and workbook compatibility
+ Preserves embedded images and updates supported references
+ Opens and saves password-encrypted Office Agile workbooks
- Formula calculation is opt-in
- Some integrations require Windows
MIT license Excel compatibility guide

PLEASE NOTE:

1) A great article on Microsoft Excel for automation, inclusing licensing issues, is available at https://support.microsoft.com/en-us/topic/considerations-for-server-side-automation-of-office-48bcfe93-8a89-47f1-0bce-017433ad79e2

2) calculation issue when re-opening in MS Excel: after Excel file has been written to disk, cell formulas are usually calculated and their results are buffered in the saved Excel file. In certain cases, MS Excel is not able to refresh calculated cell values when they depend (indirectly) on other cells which have changed.

  • This issue applies for all 3rd-party engines (as far as I know)
  • Available workaround in MS Excel: enter each single cell manually (and in correct dependency order!) and confirm its formula (and sorry, F9 for full automatic recalculation doesn't work)
  • Available workaround in Epplus 4 special edition (provided within this project, see CompuMaster.Excel.EpplusFreeFixCalcsEdition): Clear all cached values from cells with formulas to enforce MS Excel to recalculate them (without depending of any caches)

Formula syntax and evaluation culture by engine

Formula syntax covers function names, argument separators and numeric literals. For portable ExcelOps code, supply invariant formulas such as SUM(1.5,2). The evaluation culture affects operations such as parsing "1,5" as a number or formatting a month name. ExcelDataOperationsOptions.FormulaEvaluationCulture configures Open XML. The other adapters use their underlying engine's culture behavior.

Engine Formula syntax Locale-sensitive evaluation
Open XML Invariant API and workbook syntax. Sets the culture per workbook and falls back to the opening thread's culture. The guide lists precedence and worked examples. Open XML culture settings
Microsoft Excel via COM The adapter writes Range.Formula. Excel exposes localized syntax through the separate native Range.FormulaLocal property. Excel FormulaLocal reference Excel uses its language and regional settings. The adapter initializes the decimal and thousands separators from the .NET thread culture at Excel application scope. Excel regional settings API / Adapter source
CompuMaster.EPPlus4 / Free FixCalcs Invariant formula syntax. Culture handling varies by function. For example, one argument parser tries invariant numbers and then uses the current .NET culture for dates. TEXT reads separators from the current culture. Argument parser / TEXT implementation
EPPlus 8.4 English function names and commas between arguments. EPPlus formula calculation EPPlus 8.4 exposes no general evaluation culture in ExcelCalculationOption. EPPlus calculation options
Spire.XLS 13.2.4 and FreeSpire.XLS 12.7.0 Both tested versions evaluated =SUM(1.5,2) and returned #NAME? for =SUMME(1,5;2) with de-DE. Spire has a native Workbook.CultureInfo property. In both tested versions, VALUE("1,5") returned 15 with de-DE. The ExcelOps Spire adapters do not map the common option to the native property. Spire Workbook.CultureInfo reference

PDF export and printing by engine

Engine PDF output Printing
Open XML Headless worksheet, chart sheet, ordered selection and workbook PDF on Windows and Linux. File and stream output. Print-ready PDF using saved worksheet layout.
Microsoft Excel Native workbook, worksheet and chart-sheet PDF files on Windows with Excel installed. Windows printer and driver-managed print-to-file.
FreeSpire.XLS and Spire.XLS Workbook and worksheet PDF files subject to the edition's conversion limits. Windows printer and driver-managed print-to-file.
EPPlus engines PDF export unavailable through ExcelOps. ExcelOps printer output unavailable.

See the Open XML PDF guide for examples, runtime requirements and layout limits.

Common helper libraries

  • CompuMaster.EPPlus4
    • a fork of Epplus 4.5 with LGPL license, providing features to clear calculation caches which might lead to wrong calculation cache reset behavioiur in MS Excel (MS Excel doesn't recalculate all required cells)
    • Supports .NET Framework 4.8 + .NET 6 or higher
    • Feature support for checkup if cell requires recalculation: EPPlusSoftware/EPPlus#113
    • Correct refreshing of indirect cell references by resetting all calculation caches (enforces MS Excel to recalculate all cells)
  • CompuMaster.Excel.Tools.MicrosoftAndEpplus
    • Provide workarounds for some well-known issues in some of the alternative Excel engines
  • CompuMaster.Excel.MsExcelComInterop
    • Allow COM interop at clients without using Microsoft.Office.Excel.Interop assemblies for light-weight deployments of applications to customers/clients, regardless of the installed version of Microsoft Office
    • Limitation: supports only a very tiny, but often-used feature set, e.g. print, export to PDF, run VBA code

Special CompuMaster Edition

CompuMaster.EPPlus4 is this repository's maintained fork of EPPlus 4.5.3.3. See the package README for the complete CompuMaster feature list and package notes.

Added Features

  • Resets internal calculation caches so Microsoft Excel recalculates dependent formulas when reopening a workbook.
  • Fixes internal races in cell storage, style updates, and calculation/lifetime coordination; general multithreaded workbook access remains unsupported.
  • Uses zero-based worksheet indexing by default on every target framework; the existing compatibility setting can switch to one-based indexing.

Security Features

  • Uses System.IO.Compression.ZipArchive for XLSX packaging, with compatibility handling for older encrypted workbooks.
  • Limits ZIP/XML expansion and encrypted-input work when loading XLSX files; callers can adjust the defaults for trusted files.

These limits do not make arbitrary untrusted workbooks safe to parse. See the security guidance.

Known Issues

Warning: Epplus4 (including its fork CompuMaster.EPPlus4) is not thread-safe. Multithreaded use of the library is not supported. Concurrent access can cause exceptions and incorrect or lost cell values without an exception.

Use each ExcelPackage in one thread throughout its lifetime, including access to its workbook, worksheets and ranges, formula calculation, saving, and disposal. This follows Jan Källman's recommendation to avoid multiple threads on a single workbook. Different worksheets in one package are not independent concurrency boundaries. If a package must be shared, serialize all access with one stable external lock per package/workbook, including complete select/read/modify/write sequences; locks per worksheet or cell are insufficient.

The CompuMaster edition fixes the reproduced internal races in cell-store growth and access, workbook-wide style updates, and concurrent formula calculations. Calculation, parser-manager operations, saving, and disposal now share a package-local monitor. Regression tests cover these cases and independently owned packages. These internal fixes do not establish general thread safety or replace caller coordination. See issue #26 for the original failures, implementation scope, and remaining investigation items.

The following known limitations remain:

  1. A shared, cached ExcelRange can target the wrong cell. Its indexers change the range object's address and return the same object. Another thread can change that address between selection and use. This behavior is retained for compatibility; do not share cached range objects between threads.
  2. Compound operations and arbitrary concurrent workbook access remain unsupported. Internal cell-store locks do not make selection followed by reading/writing atomic, provide snapshot cell enumeration, or coordinate every cell/structure change with calculation, saving, loading, or disposal. Concurrent edits can still invalidate a traversal or produce inconsistent output. Coordinate complete operations externally, including reads; direct XML/collection mutation and copying styles between workbooks also require caller coordination.
  3. Callbacks must not reenter workbook services during calculation. Custom functions and loggers run while the package monitor is held. Recursively calculating/parsing, saving, or disposing the same package can interfere with active parser state or workbook lifetime. Waiting for another thread that needs the same package can deadlock. The monitor permits internal nested calls but does not make such callback behavior supported.
  4. Some stream copies are globally serialized. The inherited CopyStream lock can limit throughput even for independent packages. It does not make sharing a stream safe; each package must own its stream exclusively.

Use separately owned packages and streams for parallel jobs, with one thread accessing each package at a time. The independent-package regression tests cover selected operations, not every feature. Other lazy initialization paths, the shared RAND() seed, and publicly mutable operator/validation objects still require investigation; these code observations are not all demonstrated runtime defects.

Embedded worksheet pictures and charts in HTML

Open XML can include worksheet pictures and rendered charts in the shared HTML export. Select their output modes independently and use ExportChartSheets for standalone chart sheets. The HTML media guide covers each engine, examples, limits, and the behavior of file and in-memory exports.

Reviewing HTML export tests

Local test runs retain their usual browser behavior. The ExcelOps smoke tests open their generated HTML files, while the standalone Spire export tests leave them on disk. CI never launches a browser.

Set COMPUMASTER_EXCEL_HTML_VISUAL_TESTS to off to leave all exports on disk without opening them. When a change could affect the rendered HTML and you want to inspect specific exports, set the value to a comma-separated list of exact NUnit method names or full test names. A full name can select a single engine's test. HTML generation and automated checks still run in either mode.

dotnet test ExcelOpsTest/TestExcelOps.vbproj -f net8.0 --environment COMPUMASTER_EXCEL_HTML_VISUAL_TESTS=off
dotnet test ExcelOpsTest/TestExcelOps.vbproj -f net8.0 --filter FullyQualifiedName~HtmlExportWorksheetGrunddatenV19 --environment COMPUMASTER_EXCEL_HTML_VISUAL_TESTS=HtmlExportWorksheetGrunddatenV19

Licensing

  • Please see license type for every sub project within its directory
  • Pay attention to required licensing of the 3rd party components (commercial vs. community licensing, user licensing, etc.)

Examples

HTML export resource limits

Open XML, EPPlus 4 FixCalcs, EPPlus Polyform, and ClosedXML apply these defaults to a worksheet or workbook HTML export.

Limit Default
Grid positions per exported worksheet 100,000
Combined grid positions per export 500,000
Ordinary HTML in UTF-16 code units 24,000,000

The grid is the exported rectangle after applying the range options. Its size includes blanks and positions covered by merged cells. The ordinary HTML limit includes markup and escaped text. Inline data URLs and other media have separate limits. An export exceeding a limit throws HtmlExportLimitExceededException before creating or replacing a destination file. The exception supplies the limit name, the configured limit and the amount reached when it stopped the export.

Supply ResourceLimits on the export options to give a larger trusted export more room. This example raises the worksheet limit and uses the defaults for the other limits.

using CompuMaster.Excel.ExcelOps;

var options = new HtmlWorkbookExportOptions
{
    ResourceLimits = new HtmlExportResourceLimits(maxWorksheetCells: 200_000)
};
workbook.ExportWorkbookToHtml("report.html", options);

HtmlSheetExportOptions accepts the same setting for a single worksheet. Custom renderers that override the legacy HTML renderer hook continue to use that hook. Implement budgeted rendering to accept explicit limits.

Missing formula results in HTML

The EPPlus, Open XML, and ClosedXML exporters read stored formula results by default. A formula in the exported area without a result raises MissingCalculatedCellValueException, with the position and formula. Set HtmlSheetExportOptions.MissingFormulaResultText to plain text such as "#Value?", or set it to "" to explicitly leave the cell blank. The exporter HTML-encodes the replacement text. A computed empty string, zero, false, or an Excel error is a stored result.

Use HasMissingCachedFormulaResult to inspect a cell without calculating it. For direct cell reads, the overloads that accept FormulaCalculationMode require an explicit choice. UseCachedValueOnly reads the cache. CalculateIfMissing asks the engine to calculate a missing result, subject to its calculation capabilities. The earlier LookupCellValue and LookupCellValueAsObject signatures remain available to compiled callers. Recompile with the overload that takes FormulaCalculationMode, using EngineDefault to retain the engine's earlier lookup behavior. This migration mode also works with engines that do not expose a separate formula cache.

For HTML, use UseCachedValueOnly or CalculateIfMissing. Supply an empty replacement string to retain the previous blank rendering. Calculation exceptions remain visible.

Epplus 4 (LGPL)

Quick-Start: Create a workbook and put some values and formulas, then output the result to console
using CompuMaster.Excel.ExcelOps;

string FirstSheetName;
TextTable formulasOrValues;
TextTable values;

//Create a workbook and put some values and formulas
ExcelDataOperationsBase workbook = new EpplusFreeExcelDataOperations(null, ExcelDataOperationsBase.OpenMode.CreateFile, new ExcelDataOperationsOptions());
FirstSheetName = workbook.SheetNames()[0];
workbook.WriteCellValue<int>(FirstSheetName, 0, 0, 123);
workbook.WriteCellValue<double>(new ExcelCell(FirstSheetName, "B1", ExcelCell.ValueTypes.All), 456.123);
workbook.WriteCellFormula(FirstSheetName, 0, 2, @"SUM(A1:B1)", true);

//Output table with formulas or alternatively with formatted cell value
formulasOrValues = workbook.SheetContentMatrix(FirstSheetName, ExcelDataOperationsBase.MatrixContent.FormulaOrFormattedText);
System.Console.WriteLine(formulasOrValues.ToUIExcelTable());

//Output table with calculated or static values
values = workbook.SheetContentMatrix(FirstSheetName, ExcelDataOperationsBase.MatrixContent.StaticOrCalculatedValues);
System.Console.WriteLine(values.ToUIExcelTable());

leads to following output

# |A  |B      |C
--+---+-------+-----------
1 |123|456,123|=SUM(A1:B1)

# |A  |B      |C
--+---+-------+-------
1 |123|456,123|579,123

Epplus (Polyform license edition)

Quick-Start: Create a workbook and put some values and formulas, then output the result to console
using CompuMaster.Excel.ExcelOps;

string FirstSheetName;
TextTable formulasOrValues;
TextTable values;

//Assign required license context for Epplus component
EpplusPolyformExcelDataOperations.LicenseContext = new EpplusPolyformExcelDataOperations.EpplusLicenseActivator(OfficeOpenXml.EPPlusLicenseType.NonCommercialPersonal, "Your Name");

//Create a workbook and put some values and formulas
workbook = new EpplusPolyformExcelDataOperations(null, ExcelDataOperationsBase.OpenMode.CreateFile, new ExcelDataOperationsOptions());
FirstSheetName = workbook.SheetNames()[0];
workbook.WriteCellValue<int>(FirstSheetName, 0, 0, 123);
workbook.WriteCellValue<double>(new ExcelCell(FirstSheetName, "B1", ExcelCell.ValueTypes.All), 456.123);
workbook.WriteCellFormula(FirstSheetName, 0, 2, @"SUM(A1:B1)", true);

//Output table with formulas or alternatively with formatted cell value
formulasOrValues = workbook.SheetContentMatrix(FirstSheetName, ExcelDataOperationsBase.MatrixContent.FormulaOrFormattedText);
System.Console.WriteLine(formulasOrValues.ToUIExcelTable());

//Output table with calculated or static values
values = workbook.SheetContentMatrix(FirstSheetName, ExcelDataOperationsBase.MatrixContent.StaticOrCalculatedValues);
System.Console.WriteLine(values.ToUIExcelTable());

leads to following output

# |A  |B      |C
--+---+-------+-----------
1 |123|456,123|=SUM(A1:B1)

# |A  |B      |C
--+---+-------+-------
1 |123|456,123|579,123

FreeSpire.Xls

Quick-Start: Create a workbook and put some values and formulas, then output the result to console
using CompuMaster.Excel.ExcelOps;

string FirstSheetName;
TextTable formulasOrValues;
TextTable values;

//Create a workbook and put some values and formulas
workbook = new FreeSpireXlsDataOperations(null, ExcelDataOperationsBase.OpenMode.CreateFile, new ExcelDataOperationsOptions());
FirstSheetName = workbook.SheetNames()[0];
workbook.WriteCellValue<int>(FirstSheetName, 0, 0, 123);
workbook.WriteCellValue<double>(new ExcelCell(FirstSheetName, "B1", ExcelCell.ValueTypes.All), 456.123);
workbook.WriteCellFormula(FirstSheetName, 0, 2, @"SUM(A1:B1)", true);

//Output table with formulas or alternatively with formatted cell value
formulasOrValues = workbook.SheetContentMatrix(FirstSheetName, ExcelDataOperationsBase.MatrixContent.FormulaOrFormattedText);
System.Console.WriteLine(formulasOrValues.ToUIExcelTable());

//Output table with calculated or static values
values = workbook.SheetContentMatrix(FirstSheetName, ExcelDataOperationsBase.MatrixContent.StaticOrCalculatedValues);
System.Console.WriteLine(values.ToUIExcelTable());

leads to following output

# |A  |B      |C
--+---+-------+-----------
1 |123|456,123|=SUM(A1:B1)

# |A  |B      |C
--+---+-------+-------
1 |123|456,123|579,123

Microsoft Excel (via COM interop)

Quick-Start: Create a workbook and put some values and formulas, then output the result to console
using CompuMaster.Excel.ExcelOps;

string FirstSheetName;
TextTable formulasOrValues;
TextTable values;

//Create a workbook and put some values and formulas
workbook = new MsExcelDataOperations(null, ExcelDataOperationsBase.OpenMode.CreateFile, new ExcelDataOperationsOptions());
FirstSheetName = workbook.SheetNames()[0];
workbook.WriteCellValue<int>(FirstSheetName, 0, 0, 123);
workbook.WriteCellValue<double>(new ExcelCell(FirstSheetName, "B1", ExcelCell.ValueTypes.All), 456.123);
workbook.WriteCellFormula(FirstSheetName, 0, 2, @"SUM(A1:B1)", true);

//Output table with formulas or alternatively with formatted cell value
formulasOrValues = workbook.SheetContentMatrix(FirstSheetName, ExcelDataOperationsBase.MatrixContent.FormulaOrFormattedText);
System.Console.WriteLine(formulasOrValues.ToUIExcelTable());

//Output table with calculated or static values
values = workbook.SheetContentMatrix(FirstSheetName, ExcelDataOperationsBase.MatrixContent.StaticOrCalculatedValues);
System.Console.WriteLine(values.ToUIExcelTable());

leads to following output

# |A  |B      |C
--+---+-------+-----------
1 |123|456,123|=SUM(A1:B1)

# |A  |B      |C
--+---+-------+-------
1 |123|456,123|579,123

File format support by engine

The following table summarizes the expected behavior when opening static test workbooks with or without a password. Password-protected test workbooks use test as the valid password.

Engine .xlsx without password .xlsx with missing/wrong password .xlsx with correct password .xls without password .xls with missing/wrong password .xls with correct password .xlsb without password .xlsb with missing/wrong password .xlsb with correct password
Microsoft Excel Supported FilePasswordProtectedMismatchException Supported Supported FilePasswordProtectedMismatchException Supported Supported FilePasswordProtectedMismatchException Supported
EPPlus 4 / Free FixCalcs Supported FilePasswordProtectedMismatchException Supported BinaryXlsFileNotSupportedException BinaryXlsFileNotSupportedException BinaryXlsFileNotSupportedException BinaryXlsbFileNotSupportedException FilePasswordProtectedMismatchException BinaryXlsbFileNotSupportedException
EPPlus Polyform Supported FilePasswordProtectedMismatchException Supported BinaryXlsFileNotSupportedException BinaryXlsFileNotSupportedException BinaryXlsFileNotSupportedException BinaryXlsbFileNotSupportedException FilePasswordProtectedMismatchException BinaryXlsbFileNotSupportedException
Spire.Xls Supported FilePasswordProtectedMismatchException Supported Supported FilePasswordProtectedMismatchException Supported Supported FilePasswordProtectedMismatchException Supported
FreeSpire.Xls Supported FilePasswordProtectedMismatchException Supported Supported FilePasswordProtectedMismatchException Supported Supported FilePasswordProtectedMismatchException Supported
Open XML SDK Supported Unsupported Unsupported Unsupported Unsupported Unsupported Unsupported Unsupported Unsupported

About

Access and edit Excel files with common interface for several Excel engines

Resources

Stars

1 star

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages