diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 00000000..952e3ece --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,27 @@ +# Project conventions + +## Parsing and behavior + +- Reuse the existing push-based worksheet readers and handlers. Avoid parallel parsing paths, per-record objects, and unnecessary allocations during ordinary cell reading. +- Consider XLS, XLSX, Strict XLSX, XLSB, SpreadsheetML 2003 XML, and CSV when changing shared behavior. Keep format-specific limitations explicit. +- Preserve both normal and `SinglePassMode` behavior, including row ordering, gaps, field counts, reset, and navigation. +- Keep optional metadata separate from ordinary cell values. Do not implicitly change `GetValue()` or `AsDataSet()` output when adding metadata accessors. + +## Tests and fixtures + +- Put shared spreadsheet behavior in `src\ExcelDataReader.Tests\ExcelTestBase.cs` and OpenXML-only shared behavior in `ExcelOpenXmlReaderBase.cs`. Keep format-specific and parser regressions in focused suites. +- Prefer real producer-saved workbooks for compatibility coverage. Use synthetic records for malformed input and precise edge cases. +- Test applicable reading modes and formats. Include Strict XLSX when changing shared OpenXML behavior. + +## Build and validation + +- The solution is `ExcelDataReader.slnx`. CI restores with `dotnet restore --locked-mode` and builds with `dotnet build ExcelDataReader.slnx --no-restore -c Release /p:TreatWarningsAsErrors=true`. +- Run tests with `dotnet test src\ExcelDataReader.Tests\ExcelDataReader.Tests.csproj -c Release`. Use a focused `--filter` for targeted changes; Windows runs both test target frameworks. +- Never overlap build or test commands that share project outputs. +- Follow `.editorconfig` and keep formatting changes scoped to the task. +- Preserve the library's target-framework compatibility. Avoid unnecessary dependencies and SDK-version-dependent package lock changes; see the explanation in `Directory.Build.props`. + +## Public documentation + +- Add public reader APIs to the existing README API overview table and relevant usage section. +- Keep README and XML documentation focused on caller-visible behavior, support boundaries, and meaningful costs or safety caveats. Avoid unnecessary implementation details such as cache lifetime, object sharing, and parser mechanics. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..aa075fad --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,49 @@ +name: CI + +on: + push: + branches: ['develop'] + tags-ignore: ['**'] + pull_request: + +permissions: {} + +jobs: + build: + name: Build (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + permissions: + contents: read + + steps: + - uses: actions/checkout@v6 + + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 10.x + 11.x + cache: true + cache-dependency-path: | + src/**/packages.lock.json + src/**/*.csproj + Directory.Build.props + Directory.Packages.props + ExcelDataReader.slnx + + - name: Restore + run: dotnet restore ExcelDataReader.slnx --locked-mode + + - name: Build + run: dotnet build ExcelDataReader.slnx --no-restore -c Release /p:TreatWarningsAsErrors=true + + - name: Test + run: dotnet test src/ExcelDataReader.Tests/ExcelDataReader.Tests.csproj --no-build -c Release + + - name: Test without registered code pages + run: dotnet test src/ExcelDataReader.NoProvider.Tests/ExcelDataReader.NoProvider.Tests.csproj --no-build -c Release diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 00000000..c934b585 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,101 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL Advanced" + +on: + push: + branches: [ "develop" ] + pull_request: + branches: [ "develop" ] + schedule: + - cron: '32 3 * * 6' + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + # Runner size impacts CodeQL analysis time. To learn more, please see: + # - https://gh.io/recommended-hardware-resources-for-running-codeql + # - https://gh.io/supported-runners-and-hardware-resources + # - https://gh.io/using-larger-runners (GitHub.com only) + # Consider using larger runners or machines with greater resources for possible analysis time improvements. + runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} + permissions: + # required for all workflows + security-events: write + + # required to fetch internal or private CodeQL packs + packages: read + + # only required for workflows in private repositories + actions: read + contents: read + + strategy: + fail-fast: false + matrix: + include: + - language: actions + build-mode: none + - language: csharp + build-mode: none + # CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift' + # Use `c-cpp` to analyze code written in C, C++ or both + # Use 'java-kotlin' to analyze code written in Java, Kotlin or both + # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both + # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis, + # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning. + # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how + # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages + steps: + - name: Checkout repository + uses: actions/checkout@v7 + + # Add any setup steps before running the `github/codeql-action/init` action. + # This includes steps like installing compilers or runtimes (`actions/setup-node` + # or others). This is typically only required for manual builds. + # - name: Setup runtime (example) + # uses: actions/setup-example@v1 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v4 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + # If the analyze step fails for one of the languages you are analyzing with + # "We were unable to automatically build your code", modify the matrix above + # to set the build mode to "manual" for that language. Then modify this step + # to build your code. + # ℹ️ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + - name: Run manual build steps + if: matrix.build-mode == 'manual' + shell: bash + run: | + echo 'If you are using a "manual" build mode for one or more of the' \ + 'languages you are analyzing, replace this with the commands to build' \ + 'your code, for example:' + echo ' make bootstrap' + echo ' make release' + exit 1 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v4 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 00000000..05a5a3ba --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,38 @@ +name: Publish + +on: + release: + types: [published] + +permissions: {} + +jobs: + publish: + runs-on: ubuntu-latest + environment: nuget-release + permissions: + contents: read + id-token: write + + steps: + - name: Download packages from release + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ github.event.release.tag_name }} + run: gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --pattern '*.nupkg' --dir packages + + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + dotnet-version: '11.x' + + - name: NuGet login + uses: NuGet/login@v1 + id: login + with: + user: ${{ secrets.NUGET_USER }} + + - name: Publish to NuGet.org + env: + NUGET_API_KEY: ${{ steps.login.outputs.NUGET_API_KEY }} + run: dotnet nuget push packages/*.nupkg --source https://api.nuget.org/v3/index.json diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..4150f749 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,83 @@ +name: Release + +on: + push: + tags: ['v*'] + +permissions: {} + +jobs: + build: + runs-on: windows-latest + permissions: + contents: read + + steps: + - uses: actions/checkout@v6 + + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 10.x + 11.x + cache: true + cache-dependency-path: | + src/**/packages.lock.json + src/**/*.csproj + Directory.Build.props + Directory.Packages.props + ExcelDataReader.slnx + + - name: Parse version from tag + id: version + shell: pwsh + env: + TAG: ${{ github.ref_name }} + run: | + $version = $env:TAG.TrimStart('v') + $parts = $version -split '-', 2 + $prefix = $parts[0] + $suffix = if ($parts.Length -gt 1) { $parts[1] } else { '' } + "prefix=$prefix" >> $env:GITHUB_OUTPUT + "suffix=$suffix" >> $env:GITHUB_OUTPUT + + - name: Restore + run: dotnet restore --locked-mode + + - name: Build + env: + VERSION_PREFIX: ${{ steps.version.outputs.prefix }} + VERSION_SUFFIX: ${{ steps.version.outputs.suffix }} + RELEASE_NOTES: ${{ github.server_url }}/${{ github.repository }}/releases/tag/${{ github.ref_name }} + run: dotnet build ExcelDataReader.slnx --no-restore -c Release /p:TreatWarningsAsErrors=true /p:VersionPrefix=$env:VERSION_PREFIX /p:VersionSuffix=$env:VERSION_SUFFIX /p:PackageReleaseNotes=$env:RELEASE_NOTES + + - name: Test + run: dotnet test src/ExcelDataReader.Tests/ExcelDataReader.Tests.csproj --no-build -c Release + + - name: Upload packages + uses: actions/upload-artifact@v7 + with: + name: packages + path: '**/*.nupkg' + + draft-release: + needs: build + runs-on: ubuntu-latest + permissions: + contents: write + + steps: + - name: Download packages + uses: actions/download-artifact@v8 + with: + name: packages + path: packages + + - name: Create draft release + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ github.ref_name }} + run: | + if [[ "$TAG" == *-* ]]; then PRERELEASE="--prerelease"; else PRERELEASE=""; fi + gh release create "$TAG" --repo "$GITHUB_REPOSITORY" --draft --generate-notes --title "$TAG" $PRERELEASE $(find packages -name '*.nupkg') diff --git a/.gitignore b/.gitignore index 633acdbc..3c05cd30 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ !.gitignore !.gitattributes !.globalconfig +!.github # User-specific files *.suo diff --git a/Directory.build.props b/Directory.Build.props similarity index 64% rename from Directory.build.props rename to Directory.Build.props index d79eee79..e2303668 100644 --- a/Directory.build.props +++ b/Directory.Build.props @@ -1,16 +1,19 @@ ExcelDataReader developers - 13.0 + 15.0 enable true $(MSBuildThisFileDirectory)artifacts true + + false - 3.8.0 - net462;netstandard2.0;netstandard2.1;net8.0 + 4.0.0 + net462;netstandard2.0;netstandard2.1;net10.0 + enable latest-recommended ..\ExcelDataReader.snk true @@ -24,7 +27,13 @@ $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb MIT README.md - true + + true + true @@ -35,21 +44,10 @@ <_Parameter1>true - - - - all - runtime; build; native; contentfiles; analyzers - - - - - - diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 00000000..bb26b158 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,25 @@ + + + true + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ExcelDataReader.sln b/ExcelDataReader.sln deleted file mode 100644 index f06a4234..00000000 --- a/ExcelDataReader.sln +++ /dev/null @@ -1,54 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.4.33205.214 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{537D3BEA-4A18-4381-A955-DF762D21E100}" - ProjectSection(SolutionItems) = preProject - global.json = global.json - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExcelDataReader", "src\ExcelDataReader\ExcelDataReader.csproj", "{627CD303-4CE5-4300-8BD1-0FCF143D4874}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExcelDataReader.Tests", "src\ExcelDataReader.Tests\ExcelDataReader.Tests.csproj", "{A90F5580-605E-4DA6-8997-877EB8F7D024}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExcelDataReader.DataSet", "src\ExcelDataReader.DataSet\ExcelDataReader.DataSet.csproj", "{061F5E1D-23A7-4744-BF2A-54AAFC5EFE70}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExcelDataReader.Sample", "src\ExcelDataReader.Sample\ExcelDataReader.Sample.csproj", "{BCE486DF-3DA2-42A2-BF38-376B17CEF434}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExcelDataReader.Benchmarks", "src\ExcelDataReader.Benchmarks\ExcelDataReader.Benchmarks.csproj", "{A40BE62A-B8AE-44D1-8E97-DCB4DA8B8F17}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {627CD303-4CE5-4300-8BD1-0FCF143D4874}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {627CD303-4CE5-4300-8BD1-0FCF143D4874}.Debug|Any CPU.Build.0 = Debug|Any CPU - {627CD303-4CE5-4300-8BD1-0FCF143D4874}.Release|Any CPU.ActiveCfg = Release|Any CPU - {627CD303-4CE5-4300-8BD1-0FCF143D4874}.Release|Any CPU.Build.0 = Release|Any CPU - {A90F5580-605E-4DA6-8997-877EB8F7D024}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A90F5580-605E-4DA6-8997-877EB8F7D024}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A90F5580-605E-4DA6-8997-877EB8F7D024}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A90F5580-605E-4DA6-8997-877EB8F7D024}.Release|Any CPU.Build.0 = Release|Any CPU - {061F5E1D-23A7-4744-BF2A-54AAFC5EFE70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {061F5E1D-23A7-4744-BF2A-54AAFC5EFE70}.Debug|Any CPU.Build.0 = Debug|Any CPU - {061F5E1D-23A7-4744-BF2A-54AAFC5EFE70}.Release|Any CPU.ActiveCfg = Release|Any CPU - {061F5E1D-23A7-4744-BF2A-54AAFC5EFE70}.Release|Any CPU.Build.0 = Release|Any CPU - {BCE486DF-3DA2-42A2-BF38-376B17CEF434}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BCE486DF-3DA2-42A2-BF38-376B17CEF434}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BCE486DF-3DA2-42A2-BF38-376B17CEF434}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BCE486DF-3DA2-42A2-BF38-376B17CEF434}.Release|Any CPU.Build.0 = Release|Any CPU - {A40BE62A-B8AE-44D1-8E97-DCB4DA8B8F17}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A40BE62A-B8AE-44D1-8E97-DCB4DA8B8F17}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A40BE62A-B8AE-44D1-8E97-DCB4DA8B8F17}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A40BE62A-B8AE-44D1-8E97-DCB4DA8B8F17}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {80B8A8D2-CD7F-499C-8A39-898C846DF211} - EndGlobalSection -EndGlobal diff --git a/ExcelDataReader.slnx b/ExcelDataReader.slnx new file mode 100644 index 00000000..25a1a49c --- /dev/null +++ b/ExcelDataReader.slnx @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/ExcelDataReader.sln.DotSettings b/ExcelDataReader.slnx.DotSettings similarity index 100% rename from ExcelDataReader.sln.DotSettings rename to ExcelDataReader.slnx.DotSettings diff --git a/LICENSE b/LICENSE index 137d754a..917115f9 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014 ExcelDataReader +Copyright (c) 2014-2026 ExcelDataReader contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 9374a76e..ff0fb82a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # ExcelDataReader -[![NuGet](https://img.shields.io/nuget/v/ExcelDataReader.svg)](https://www.nuget.org/packages/ExcelDataReader) +[![NuGet](https://img.shields.io/nuget/v/ExcelDataReader.svg)](https://www.nuget.org/packages/ExcelDataReader) [![CI](https://github.com/ExcelDataReader/ExcelDataReader/actions/workflows/ci.yml/badge.svg?branch=develop)](https://github.com/ExcelDataReader/ExcelDataReader/actions/workflows/ci.yml) Lightweight and fast library written in C# for reading Microsoft Excel files (2.0-2021, 365). @@ -8,62 +8,67 @@ Please feel free to fork and submit pull requests to the develop branch. If you are reporting an issue it is really useful if you can supply an example Excel file as this makes debugging much easier and without it we may not be able to resolve any problems. -## Continuous integration - -| Branch | Build status | -|---------|--------------| -| develop | [![Build status](https://ci.appveyor.com/api/projects/status/ii6hbs9otpbg1nqh/branch/develop?svg=true)](https://ci.appveyor.com/project/andersnm/exceldatareader/branch/develop) | -| master | [![Build status](https://ci.appveyor.com/api/projects/status/ii6hbs9otpbg1nqh/branch/master?svg=true)](https://ci.appveyor.com/project/andersnm/exceldatareader/branch/master) | - ## Supported file formats and versions | File Type | Container Format | File Format | Excel Version(s) | | --------- | ---------------- | ----------- | ---------------- | | .xlsx | ZIP, CFB+ZIP | OpenXml | 2007 and newer | | .xlsb | ZIP, CFB | OpenXml | 2007 and newer | -| .xls | CFB | BIFF8 | 97, 2000, XP, 2003
98, 2001, v.X, 2004 (Mac) | -| .xls | CFB | BIFF5 | 5.0, 95 | -| .xls | - | BIFF4 | 4.0 | -| .xls | - | BIFF3 | 3.0 | -| .xls | - | BIFF2 | 2.0, 2.2 | -| .csv | - | CSV | (All) | +| .xls | CFB | BIFF8 [*](#code-page-support) | 97, 2000, XP, 2003
98, 2001, v.X, 2004 (Mac) | +| .xls | CFB | BIFF5 [*](#code-page-support) | 5.0, 95 | +| .xls | - | BIFF4 [*](#code-page-support) | 4.0 | +| .xls | - | BIFF3 [*](#code-page-support) | 3.0 | +| .xls | - | BIFF2 [*](#code-page-support) | 2.0, 2.2 | +| .xml | - | SpreadsheetML | 2002, 2003 (XML Spreadsheet) | +| .csv | - | CSV [*](#code-page-support) | (All) | + +\* See [Code page support](#code-page-support) for details. + +For compound files, required workbook and encryption streams must not exceed 2,147,483,647 bytes. -## Finding the binaries +## Installation -It is recommended to use NuGet through the VS Package Manager Console `Install-Package ` or using the VS "Manage NuGet Packages..." extension. +ExcelDataReader 2.x was distributed as a single package. Starting with version 3.0, it is distributed in two packages: -As of ExcelDataReader version 3.0, the project was split into multiple packages: +Both packages support .NET Framework 4.6.2, .NET Standard 2.0 and 2.1, and .NET 10 or later. -Install the `ExcelDataReader` base package to use the "low level" reader interface. Compatible with net462, netstandard2.0 and netstandard2.1. +Install the `ExcelDataReader` base package to use the low-level reader interface: -Install the `ExcelDataReader.DataSet` extension package to use the `AsDataSet()` method to populate a `System.Data.DataSet`. This will also pull in the base package. Compatible with net462, netstandard2.0 and netstandard2.1. +```sh +dotnet add package ExcelDataReader +``` + +To use the `AsDataSet()` method to populate a `System.Data.DataSet`, install `ExcelDataReader.DataSet`. It also pulls in the base package: + +```sh +dotnet add package ExcelDataReader.DataSet +``` ## How to use +For low-level row-by-row reading, use `CreateReader()` to auto-detect the file format: + ```c# using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read)) +using (var reader = ExcelReaderFactory.CreateReader(stream)) { - // Auto-detect format, supports: - // - Binary Excel files (2.0-2003 format; *.xls) - // - OpenXml Excel files (2007 format; *.xlsx, *.xlsb) - using (var reader = ExcelReaderFactory.CreateReader(stream)) + do { - // Choose one of either 1 or 2: - - // 1. Use the reader methods - do + while (reader.Read()) { - while (reader.Read()) - { - // reader.GetDouble(0); - } - } while (reader.NextResult()); + // reader.GetDouble(0); + } + } while (reader.NextResult()); +} +``` - // 2. Use the AsDataSet extension method - var result = reader.AsDataSet(); +To populate a `DataSet` instead, use the `AsDataSet()` extension method from the `ExcelDataReader.DataSet` package: - // The result of each spreadsheet is in result.Tables - } +```c# +using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read)) +using (var reader = ExcelReaderFactory.CreateReader(stream)) +{ + var result = reader.AsDataSet(); } ``` @@ -71,11 +76,11 @@ using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read)) Use `ExcelReaderFactory.CreateCsvReader` instead of `CreateReader` to parse a stream of plain text with comma separated values. -See also the configuration options `FallbackEncoding` and `AutodetectSeparators`. +Use `AutodetectSeparators` to configure possible delimiters, including multi-character delimiters such as `["||"]`. The selected delimiter is available through `reader.CsvSeparator`. Set `FallbackEncoding` when reading files that are not UTF-8 and have no encoding marker. -The input CSV is always parsed once completely to set FieldCount, RowCount, Encoding, Separator (or twice if the CSV lacks BOM and is not UTF8), and then parsed once again while iterating the row records. Throws `System.Text.DecoderFallbackException` if the input cannot be parsed with the specified encoding. +By default, the reader examines the whole file during initialization to determine its column and row counts. For large files, set `AnalyzeInitialCsvRows` to limit this analysis to the specified number of rows. `RowCount` is unavailable when this option is enabled, and `FieldCount` is based on the sampled rows. -The reader returns all CSV field values as strings and makes no attempts to convert the data to numbers or dates. This caller is responsible for interpreting the CSV data. +All CSV field values are returned as strings. The caller is responsible for converting them to numbers, dates, or other types. ### Using the reader methods @@ -86,24 +91,105 @@ The `AsDataSet()` extension method is a convenient helper for quickly getting th |-----------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `Read()` | reads a row from the current sheet. | | `NextResult()` | advances the cursor to the next sheet. | +| `Reset()` | restarts reading from the first sheet. | +| `ResetWorksheet()` | restarts reading the current sheet, including after its last row. The next `Read()` returns its first row; a sheet must still be selected. | | `ResultsCount` | returns the number of sheets in the current workbook. | | `Name` | returns the name of the current sheet. | | `CodeName` | returns the VBA code name identifier of the current sheet. | | `FieldCount` | returns the number of columns in the current sheet. | | `RowCount` | returns the number of rows in the current sheet. This includes terminal empty rows which are otherwise excluded by AsDataSet(). Throws `InvalidOperationException` on CSV files when used with `AnalyzeInitialCsvRows`. | +| `Depth` | always returns `0` because ExcelDataReader does not expose nested result sets. | | `HeaderFooter` | returns an object with information about the headers and footers, or `null` if there are none. | | `MergeCells` | returns an array of merged cell ranges in the current sheet. | | `RowHeight` | returns the visual height of the current row in points. May be 0 if the row is hidden. | | `GetColumnWidth()` | returns the width of a column in character units. May be 0 if the column is hidden. | -| `GetFieldType()` | returns the type of a value in the current row. Always one of the types supported by Excel: `double`, `int`, `bool`, `DateTime`, `TimeSpan`, `string`, or `null` if there is no value. | -| `IsDBNull()` | checks if a value in the current row is null. | -| `GetValue()` | returns a value from the current row as an `object`, or `null` if there is no value. | +| `GetFieldType()` | returns the type of a value in the current row. Always one of the types supported by Excel: `double`, `int`, `bool`, `DateTime`, `TimeSpan`, `string`, or `typeof(DBNull)` if there is no value. | +| `IsDBNull()` | returns `true` if a value in the current row is `DBNull` (i.e. the cell is empty). | +| `GetValue()` | returns a value from the current row as an `object`, or `DBNull.Value` if there is no value. | | `GetDouble()`
`GetInt32()`
`GetBoolean()`
`GetDateTime()`
`GetString()` | return a value from the current row cast to their respective type. | | `GetNumberFormatString()` | returns a string containing the formatting codes for a value in the current row, or `null` if there is no value. See also the Formatting section below. | | `GetNumberFormatIndex()` | returns the number format index for a value in the current row. Index values below 164 refer to built-in number formats, otherwise indicate a custom number format. | | `GetCellStyle()` | returns an object containing style information for a cell in the current row: indent, horizontal alignment, hidden, locked. | +| `CsvSeparator` | returns the selected CSV delimiter, including multi-character delimiters. Available immediately after `CreateCsvReader()`; returns `null` for non-CSV formats, disabled separator detection, or no selected result. | +| `GetComment()` | returns an immutable comment for a cell in the current row, or `null` if none is supported. Loaded lazily; see [Cell comments](#cell-comments). | +| `GetHyperlink()` | returns an immutable explicit hyperlink for a cell in the current row, or `null` if none is supported. Loaded lazily; see [Hyperlinks](#hyperlinks). | +| `DocumentProperties` | returns immutable workbook document properties, loaded on first access for XLS, XLSX, and XLSB. See [Document properties](#document-properties). | | The typed `Get*()` methods | throw `InvalidCastException` unless the types match exactly. | +Supported value and cell-metadata accessors require a current row and throw `InvalidOperationException` before the first successful `Read()` or after it returns `false`. With a current row, they throw `IndexOutOfRangeException` when the index is negative or at least `FieldCount`. `GetColumnWidth()` uses the same bounds but does not require a current row. + +### Cell comments + +`GetComment(columnIndex)` returns an immutable `CellCommentThread` for the current +row, or `null` when there is no supported comment. Its read-only `Messages` +collection contains one `CellCommentMessage` for a legacy note, with `Author` +and plain `Text`. The author is `null` for older XLS formats without author data. +Legacy notes are supported in XLS, XLSX, XLSB and SpreadsheetML; modern threaded +comments are not yet read. CSV always returns `null`. Rich-text formatting, +note layout and automatic DataSet export are not included. + +Call `Read()` successfully before accessing a comment. Comments are loaded on +first access, which may require an additional worksheet scan. Reading comments +does not change cell values or DataSet output. + +### Hyperlinks + +`GetHyperlink(columnIndex)` returns an immutable `CellHyperlink` for the current +row, or `null` when there is no supported explicit hyperlink. XLS (BIFF8), XLSX, XLSB +and SpreadsheetML are supported; CSV returns `null`. Formula-generated links +and unsupported hyperlink representations are not read. + +```c# +while (reader.Read()) +{ + var value = reader.GetValue(0); // Cell values are unchanged. + var link = reader.GetHyperlink(0); + var address = link?.Address; + var tooltip = link?.Tooltip; +} +``` + +`Address` contains the complete destination, such as +`https://example.com/report.xlsx#Summary!A1`, `#SalesTotals` or +`report.xlsx#Summary!A1`. Relative paths and stored escaping are preserved; +destinations and defined names are not validated or resolved. An address can +be empty when a stored hyperlink contains only a tooltip. + +Hyperlinks are loaded on first access, which may require an additional worksheet +scan. Reading hyperlinks does not change cell values or DataSet output. + +To use hyperlink addresses instead of cell values in `AsDataSet()`, configure +`TransformValue`. Cells without hyperlinks keep their original values: + +```c# +var result = reader.AsDataSet(new ExcelDataSetConfiguration() +{ + ConfigureDataTable = _ => new ExcelDataTableConfiguration() + { + TransformValue = (rowReader, i, value) => + rowReader.GetHyperlink(i)?.Address ?? value + } +}); +``` + +### Document properties + +`reader.DocumentProperties` exposes the workbook's `Title`, `Subject`, `Author`, +`Keywords`, `Description`, `LastModifiedBy`, `Created`, `Modified` and +`LastPrinted`. For XLS, XLSX and XLSB, the immutable object is loaded on first +access while the reader is open, independently of the selected worksheet and +`SinglePassMode`. Values loaded before closing remain available afterward; if +the properties were not accessed before closing, accessing them throws +`InvalidOperationException`. SpreadsheetML properties are read during its +workbook XML scan and remain available after close. Dates are returned as UTC +`DateTime` values; absent or unsupported properties are `null`. + +XLS, XLSX, XLSB and SpreadsheetML are supported. CSV and raw BIFF streams have +no document properties. These are stored document properties, not filesystem +attributes; `Description` corresponds to Excel's document Comments property, +not cell comments. Custom properties are not exposed. Invalid optional property +values are ignored without changing worksheet values. + ### CreateReader() configuration options The `ExcelReaderFactory.CreateReader()`, `CreateBinaryReader()`, `CreateOpenXmlReader()`, `CreateCsvReader()` methods accept an optional configuration object to modify the behavior of the reader: @@ -111,36 +197,73 @@ The `ExcelReaderFactory.CreateReader()`, `CreateBinaryReader()`, `CreateOpenXmlR ```c# var reader = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration() { - // Gets or sets the encoding to use when the input XLS lacks a CodePage - // record, or when the input CSV lacks a BOM and does not parse as UTF8. + // Encoding to use when the input XLS lacks a CodePage record, + // or when the input CSV lacks a BOM and does not parse as UTF8. // Default: cp1252 (XLS BIFF2-5 and CSV only) - FallbackEncoding = Encoding.GetEncoding(1252), + // FallbackEncoding = Encoding.UTF8, - // Gets or sets the password used to open password protected workbooks. + // Password used to open password-protected workbooks. Password = "password", - // Gets or sets an array of CSV separator candidates. The reader - // autodetects which best fits the input data. Default: , ; TAB | # - // (CSV only) - AutodetectSeparators = new char[] { ',', ';', '\t', '|', '#' }, + // CSV separator candidates. The reader autodetects which best fits the input data. + // Default: , ; TAB | # (CSV only) + AutodetectSeparators = new string[] { ",", ";", "\t", "|", "#" }, + + // Quote character for CSV. Default: " (CSV only) + QuoteChar = '"', - // Gets or sets a value indicating whether to trim white space values for CSV (Default 'true'). - // (CSV only) + // Trim whitespace around CSV fields. Default: true (CSV only) TrimWhiteSpace = true, - // Gets or sets a value indicating whether to leave the stream open after - // the IExcelDataReader object is disposed. Default: false + // Leave the stream open after the reader is disposed. Default: false LeaveOpen = false, - // Gets or sets a value indicating the number of rows to analyze for - // encoding, separator and field count in a CSV. When set, this option - // causes the IExcelDataReader.RowCount property to throw an exception. - // Default: 0 - analyzes the entire file (CSV only, has no effect on other - // formats) + // Number of CSV rows to analyze for encoding, separator and field count. + // When nonzero, accessing RowCount throws an exception. + // Default: 0 - analyzes the entire file (CSV only) AnalyzeInitialCsvRows = 0, + + // Read without determining the full worksheet size upfront. When true, RowCount + // throws InvalidOperationException and FieldCount grows dynamically as + // rows are read. Default: false + // (XLS, XLSX/XLSB, and SpreadsheetML only, has no effect on CSV) + SinglePassMode = false, + + // Escape character for CSV quoted fields. When set, this + // character inside a quoted field escapes the next character, e.g. set to + // '\\' to support \" as an escaped quote. Not part of RFC 4180; only + // enable when reading files that use backslash-style escaping. + // Default: null - disabled (CSV only) + EscapeChar = null, }); ``` +Non-seekable input streams are buffered in memory before reading. + +### Large shared string tables + +XLSX, XLSB, and BIFF8 XLS files can contain large shared string tables (SSTs). By default, the entire table is kept in memory. Use `SpillToDisk` to move the table to temporary files when it exceeds a configurable memory threshold: + +| `SharedStringStorageMode` | Behavior | +|---|---| +| `Default` | Keep the entire shared string table in memory; no temporary SST files. | +| `SpillToDisk` | Keep the shared string table in memory until it exceeds the configured threshold, then move it to temporary files. | + +```c# +using var reader = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration +{ + SharedStringStorageMode = SharedStringStorageMode.SpillToDisk, + SharedStringSpillThreshold = 64L * 1024 * 1024, // bytes; default 64 MiB, minimum 1 MiB + SharedStringTemporaryDirectory = null, // system temporary directory by default +}); +``` + +Spilling to disk reduces memory used by the shared string table but can make reading slower. The threshold applies separately to each reader and is not a limit on total memory usage, including data accumulated by `AsDataSet()`. + +Temporary files require an existing writable directory and sufficient disk space. They contain **plaintext even for password-protected workbooks** and are released by `Close()`/`Dispose()`, independently of `LeaveOpen`. Disk failures propagate without falling back to unbounded RAM. + +See [shared string storage details and benchmarks](src/ExcelDataReader.Benchmarks/SharedStringStorage.md) for memory accounting, file handling, and performance measurements. + ### AsDataSet() configuration options The `AsDataSet()` method accepts an optional configuration object to modify the behavior of the DataSet conversion: @@ -148,55 +271,59 @@ The `AsDataSet()` method accepts an optional configuration object to modify the ```c# var result = reader.AsDataSet(new ExcelDataSetConfiguration() { - // Gets or sets a value indicating whether to set the DataColumn.DataType - // property in a second pass. + // Set the DataColumn.DataType property in a second pass. UseColumnDataType = true, - // Gets or sets a callback to determine whether to include the current sheet - // in the DataSet. Called once per sheet before ConfigureDataTable. + // Include the current sheet in the DataSet. + // Called once per sheet before ConfigureDataTable. FilterSheet = (tableReader, sheetIndex) => true, - // Gets or sets a callback to obtain configuration options for a DataTable. + // Configure each DataTable. ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration() { - // Gets or sets a value indicating the prefix of generated column names. + // Whether the DataTable should be case sensitive. + // Useful when setting a primary key after loading from Excel. + CaseSensitive = false, + + // Prefix of generated column names. EmptyColumnNamePrefix = "Column", - // Gets or sets a value indicating whether to use a row from the - // data as column names. + // Use a row from the data as column names. UseHeaderRow = false, - // Gets or sets a callback to determine which row is the header row. + // Select which row is the header row. // Only called when UseHeaderRow = true. ReadHeaderRow = (rowReader) => { // F.ex skip the first row and use the 2nd row as column headers: rowReader.Read(); }, - // Gets or sets a callback to determine whether to include the - // current row in the DataTable. + // Include the current row in the DataTable. FilterRow = (rowReader) => { return true; }, - // Gets or sets a callback to determine whether to include the specific - // column in the DataTable. Called once per column after reading the - // headers. + // Include the specific column in the DataTable. + // Called once per column after reading the headers. FilterColumn = (rowReader, columnIndex) => { return true; - } + }, + + // Fill merged cells with their top-left cell's value. Default: false + FillMergedCellsValue = false, } }); ``` Setting up `AsDataSet()` configuration, use the FilterRow callback to implement a "progress indicator" while loading, e.g.: ```c# +int currentRow = 0; var result = reader.AsDataSet(new ExcelDataSetConfiguration() { ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration() { FilterRow = (rowReader) => { - int progress = (int)Math.Ceiling((decimal)rowReader.Depth / (decimal)rowReader.RowCount * (decimal)100); + int progress = (int)Math.Ceiling((decimal)++currentRow / (decimal)rowReader.RowCount * (decimal)100); // progress is in the range 0..100 return true; } @@ -206,7 +333,9 @@ var result = reader.AsDataSet(new ExcelDataSetConfiguration() ## Formatting -ExcelDataReader does not support formatting directly. Users may retreive the number format string for a cell through `IExcelDataReader.GetNumberFormatString(i)` and use the third party ExcelNumberFormat library for formatting purposes. +ExcelDataReader does not support formatting directly. Users may retrieve the number format string for a cell through `IExcelDataReader.GetNumberFormatString(i)` and use the third party ExcelNumberFormat library for formatting purposes. + +`GetNumberFormatString(i)` returns Excel's original locale-independent built-in format strings. To get locale-specific date and time format strings for built-in number format indices 14–17 and 22, use the overload `GetNumberFormatString(i, provider)` with a `CultureInfo` or `DateTimeFormatInfo`. Passing `null` is equivalent to calling the no-argument overload. Example helper method using ExcelDataReader and ExcelNumberFormat to format a value: @@ -214,7 +343,7 @@ Example helper method using ExcelDataReader and ExcelNumberFormat to format a va string GetFormattedValue(IExcelDataReader reader, int columnIndex, CultureInfo culture) { var value = reader.GetValue(columnIndex); - var formatString = reader.GetNumberFormatString(columnIndex); + var formatString = reader.GetNumberFormatString(columnIndex, culture); if (formatString != null) { var format = new NumberFormat(formatString); @@ -228,7 +357,114 @@ See also: - https://github.com/andersnm/ExcelNumberFormat - https://www.nuget.org/packages/ExcelNumberFormat -## Important note when upgrading from ExcelDataReader 2.x +## Upgrading from 3.x to 4.0 + +### Cell access after the last row + +Value and cell-metadata accessors now consistently throw `InvalidOperationException` after `Read()` returns `false`. Previously, some retained access to the last row. + +### Column width index validation + +`GetColumnWidth()` now throws `IndexOutOfRangeException` for negative indices or indices at or above `FieldCount`. Previously, negative indices typically returned the default width, and indices at or above `FieldCount` threw `ArgumentException`. + +### Unsupported XLS code pages + +An XLS file declaring an unsupported code page now throws instead of retaining the previous encoding for unrecognized IDs. Code page 0 is also rejected. `FallbackEncoding` is used for BIFF2-5 files without a code page, not for unsupported code pages. + +### Date and duration precision + +Numeric date and duration values are converted to `DateTime` or `TimeSpan` at tick precision rather than being rounded to milliseconds. Excel can display distinct underlying serial values identically, while ExcelDataReader retains their tick-level differences. For multi-section number formats, the selected section now determines whether a value is converted, so `GetValue()` and `AsDataSet()` column types can differ according to the cell value and format conditions. Durations that cannot be represented as a `TimeSpan` remain numeric instead of throwing. + +### Logging API removed + +The unused `ExcelDataReader.Log` API (`Log`, `LogManager`, `ILog`, `ILogFactory`, and `NullLogFactory`) has been removed. Remove any logger initialization or implementations of these interfaces. + +### CSV separator candidates are strings + +`AutodetectSeparators` changed from `char[]` to `string[]` to support multi-character delimiters. Replace character literals such as `[',', ';']` with string literals such as `[",", ";"]`. + +### Null cells now return `DBNull.Value` instead of `null` + +`GetValue()` now returns `DBNull.Value` instead of `null` for empty cells, aligning with the `IDataReader` contract. `GetFieldType()` correspondingly returns `typeof(DBNull)` instead of `null`. + +**Before (3.x):** +```c# +var value = reader.GetValue(i); +if (value == null) +{ + // cell is empty +} +``` + +**After (4.0):** +```c# +if (reader.IsDBNull(i)) +{ + // cell is empty +} +// or +var value = reader.GetValue(i); +if (value is DBNull) +{ + // cell is empty +} +``` + +The typed getters (`GetString()`, `GetBoolean()`, `GetDateTime()`, etc.) will throw `InvalidCastException` when called on an empty cell. Always check `IsDBNull(i)` first: + +```c# +// Before (3.x): returned null for empty cells +string value = reader.GetString(i); + +// After (4.0): throws InvalidCastException for empty cells — check first +string? value = reader.IsDBNull(i) ? null : reader.GetString(i); +``` + +### `GetValue()` returns `DateTime` instead of `DateTimeOffset` for strict OpenXml dates + +In strict OpenXml mode, date values were previously returned as `DateTimeOffset`. They are now returned as `DateTime`, consistent with all other date handling in ExcelDataReader. + +```c# +// Before (3.x) +var value = (DateTimeOffset)reader.GetValue(i); + +// After (4.0) +var value = reader.GetDateTime(i); // or (DateTime)reader.GetValue(i) +``` + +### Non-seekable input streams are now supported + +Non-seekable input streams previously caused an exception. They are now fully buffered in memory before reading, so memory usage grows with the input size. + +### Row ordering and single-pass mode + +By default, XLSX and XLSB readers return rows in ascending row-index order and combine repeated entries for the same row, even when separated by other rows in the file. For duplicate cells, the last value in file order wins; the last entry for a row determines its height and hidden state. Reordering can require additional memory, up to buffering the entire worksheet for severely out-of-order input. + +With `SinglePassMode = true`, consecutive entries for the same row are still combined, but out-of-order rows or revisits to completed rows throw `ExcelDataReader.Exceptions.SinglePassRowOrderException`. Single-pass XLS reading throws the same exception for out-of-order cells. It derives from `InvalidOperationException`. Reopen the workbook with `SinglePassMode = false` and restart processing; rows may already have been returned. + +### Extensible Encryption exception type changed + +Workbooks using Extensible Encryption remain unsupported. Recognized Extensible Encryption versions now throw `NotSupportedException` instead of `InvalidOperationException`. Update any exception handling that specifically catches the previous type for this case. + +### Exceptions for malformed workbook content + +Some explicit checks for malformed XLS records and missing required encryption attributes now throw `ExcelReaderException` instead of `ArgumentException`, `IndexOutOfRangeException`, or `XmlException`. Update handlers that relied on those specific types. Other failures, including XML parsing and ZIP errors, can still throw standard .NET exceptions. + +### `TransformValue` callback parameter types changed to nullable + +The `ExcelDataTableConfiguration.TransformValue` delegate type changed from `Func` to `Func`. If you assigned a named method to this property, update its signature: + +```c# +// Before (3.x) +object MyTransform(IExcelDataReader reader, int col, object value) => ...; + +// After (4.0) +object? MyTransform(IExcelDataReader reader, int col, object? value) => ...; +``` + +Anonymous lambdas are unaffected — the compiler infers the parameter types automatically. + +## Upgrading from 2.x to 3.x ExcelDataReader 3 had some breaking changes, and older code may produce error messages similar to: @@ -255,14 +491,16 @@ var result = reader.AsDataSet(new ExcelDataSetConfiguration() }); ``` -## Important note on .NET Core +## Code page support + +ExcelDataReader resolves code pages declared in XLS files across BIFF versions, including BIFF8; if a declared code page cannot be resolved, reading throws. For BIFF2-5 files without a `CodePage` record, and for CSV files without a BOM that are not valid UTF-8, it uses `FallbackEncoding` instead; this option defaults to Windows-1252. -By default, ExcelDataReader throws a NotSupportedException "No data is available for encoding 1252." on .NET Core and .NET 5.0 or later. +On .NET 10 or later, when resolving an XLS-declared code page or the default Windows-1252 `FallbackEncoding`, the .NET 10 library target first calls `Encoding.GetEncoding`. If that lookup fails, it tries `CodePagesEncodingProvider` for the requested code page, so supported legacy encodings can be used without registering the provider globally. This fallback has a small exception-handling cost. Registering the provider during application initialization lets the first lookup succeed directly, avoiding that cost, but affects the entire application; the library does not register it globally. -To fix, add a dependency to the package `System.Text.Encoding.CodePages` and then add code to register the code page provider during application initialization (f.ex in Startup.cs): +The .NET Standard targets do not include `CodePagesEncodingProvider`. When using one of these targets on a runtime that does not support a requested code page by default, the lookup throws unless your application references the `System.Text.Encoding.CodePages` package and registers the provider during initialization: ```c# System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); ``` -This is required to parse strings in binary BIFF2-5 Excel documents encoded with DOS-era code pages. These encodings are registered by default in the full .NET Framework, but not on .NET Core and .NET 5.0 or later. +The full .NET Framework supports many legacy code pages without registration. diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 9f76a17c..00000000 --- a/appveyor.yml +++ /dev/null @@ -1,27 +0,0 @@ -version: build-{build} -skip_tags: true -image: Visual Studio 2022 -configuration: Release -build_script: -- ps: |- - If ($Env:APPVEYOR_REPO_BRANCH -eq "master") { - $Env:VERSION_SUFFIX="" - } Else { - $Env:VERSION_SUFFIX=$Env:APPVEYOR_REPO_BRANCH + $Env:APPVEYOR_BUILD_NUMBER.PadLeft(5, "0") - } - msbuild /t:Restore /p:VersionSuffix=$Env:VERSION_SUFFIX - msbuild ExcelDataReader.sln /verbosity:minimal /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" /p:Configuration=$Env:CONFIGURATION /p:VersionSuffix=$Env:VERSION_SUFFIX /p:TreatWarningsAsErrors=true -test_script: -- ps: |- - # run tests - dotnet test src\ExcelDataReader.Tests\ExcelDataReader.Tests.csproj --no-build --logger "trx" -c $Env:CONFIGURATION --results-directory artifacts\testresults - $testexitcode = $LastExitCode - # upload results to AppVeyor - $wc = New-Object 'System.Net.WebClient' - Resolve-Path .\artifacts\testresults\*.trx | % { $wc.UploadFile("https://ci.appveyor.com/api/testresults/mstest/$($env:APPVEYOR_JOB_ID)", "$_") } - if ($testexitcode -ne 0) - { - exit 1 - } -artifacts: -- path: '**\*.nupkg' diff --git a/src/ExcelDataReader.Benchmarks/BuiltinNumberFormatConstruction.cs b/src/ExcelDataReader.Benchmarks/BuiltinNumberFormatConstruction.cs new file mode 100644 index 00000000..39e45684 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/BuiltinNumberFormatConstruction.cs @@ -0,0 +1,23 @@ +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class BuiltinNumberFormatConstruction +{ + private readonly BuiltinNumberFormats _formats = new() { Keys = "common" }; + + [GlobalSetup] + public void Setup() => _formats.Setup(); + + [Benchmark(Baseline = true)] + public object Dictionary() => _formats.CreateDictionary(); + + [Benchmark] + public object Array() => _formats.CreateArray(); + +#if NET8_0_OR_GREATER + [Benchmark] + public object Frozen() => _formats.CreateFrozen(); +#endif +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/BuiltinNumberFormats.cs b/src/ExcelDataReader.Benchmarks/BuiltinNumberFormats.cs new file mode 100644 index 00000000..12d0aae5 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/BuiltinNumberFormats.cs @@ -0,0 +1,94 @@ +using System.Reflection; +using BenchmarkDotNet.Attributes; +using ExcelDataReader.Core.NumberFormat; +#if NET8_0_OR_GREATER +using System.Collections.Frozen; +#endif + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class BuiltinNumberFormats +{ + private Dictionary _dictionary = null!; + private NumberFormatString[] _array = null!; + private int[] _indices = []; +#if NET8_0_OR_GREATER + private FrozenDictionary _frozen = null!; +#endif + + [Params("common", "all", "mixed")] + public string Keys { get; set; } = string.Empty; + + [GlobalSetup] + public void Setup() + { + var type = typeof(ExcelReaderFactory).Assembly.GetType("ExcelDataReader.Core.BuiltinNumberFormat")!; + var get = type.GetMethod("GetBuiltinNumberFormat", BindingFlags.Public | BindingFlags.Static, null, [typeof(int)], null)!; + _dictionary = []; + for (int i = 0; i < 82; i++) + { + if (get.Invoke(null, [i]) is NumberFormatString value) + _dictionary.Add(i, value); + } + + _array = CreateArray(); +#if NET8_0_OR_GREATER + _frozen = CreateFrozen(); +#endif + int[] keys = Keys switch + { + "common" => [0, 0, 0, 0, 1, 2, 4, 9, 14, 14, 20, 22, 49], + "all" => Enumerable.Range(0, 82).ToArray(), + _ => [-1, 0, 2, 14, 23, 26, 49, 63, 66, 81, 82, 164, 65535, int.MaxValue], + }; + _indices = Enumerable.Range(0, 1024).Select(i => keys[i % keys.Length]).ToArray(); + if (DictionaryLookup() != ArrayLookup()) + throw new InvalidOperationException("Lookup results differ."); +#if NET8_0_OR_GREATER + if (DictionaryLookup() != FrozenLookup()) + throw new InvalidOperationException("Frozen lookup results differ."); +#endif + } + + [Benchmark(Baseline = true, OperationsPerInvoke = 1024)] + public int DictionaryLookup() + { + int count = 0; + foreach (int index in _indices) + count += _dictionary.TryGetValue(index, out var value) && value != null ? 1 : 0; + return count; + } + + [Benchmark(OperationsPerInvoke = 1024)] + public int ArrayLookup() + { + int count = 0; + foreach (int index in _indices) + count += (uint)index < (uint)_array.Length && _array[index] != null ? 1 : 0; + return count; + } + +#if NET8_0_OR_GREATER + [Benchmark(OperationsPerInvoke = 1024)] + public int FrozenLookup() + { + int count = 0; + foreach (int index in _indices) + count += _frozen.TryGetValue(index, out var value) && value != null ? 1 : 0; + return count; + } + + internal FrozenDictionary CreateFrozen() => _dictionary.ToFrozenDictionary(); +#endif + + internal NumberFormatString[] CreateArray() + { + var result = new NumberFormatString[82]; + foreach (var pair in _dictionary) + result[pair.Key] = pair.Value; + return result; + } + + internal Dictionary CreateDictionary() => new(_dictionary); +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/CellComments.cs b/src/ExcelDataReader.Benchmarks/CellComments.cs new file mode 100644 index 00000000..553b536a --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/CellComments.cs @@ -0,0 +1,94 @@ +#nullable enable + +using System.Text; +using BenchmarkDotNet.Attributes; +using ExcelDataReader.TestFixtures; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class CellComments +{ + private byte[] _data = []; + private IExcelDataReader _cachedReader = null!; + private int _column; + + [Params("xls", "xlsx", "xlsb", "xml")] + public string Format { get; set; } = string.Empty; + + [Params(false, true)] + public bool HasComments { get; set; } + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + if (!HasComments && Format == "xml") + { + _data = AllocationTestWorkbook.CreateSpreadsheetXml(Enumerable.Repeat("value", 10000).ToArray()); + } + else + { + string name = HasComments ? "OldIssue11573_BlankValues" : "10x10000"; + using var source = typeof(CellComments).Assembly.GetManifestResourceStream($"ExcelDataReader.Benchmarks.{name}.{Format}")!; + using var buffer = new MemoryStream(); + source.CopyTo(buffer); + _data = buffer.ToArray(); + } + + _cachedReader = Open(); + _cachedReader.Read(); + if (HasComments) + _cachedReader.Read(); + _column = HasComments ? 2 : 0; + _ = _cachedReader.GetComment(_column); + } + + [GlobalCleanup] + public void Cleanup() => _cachedReader.Dispose(); + + [Benchmark(Baseline = true)] + public int ReadWithoutComments() + { + using var reader = Open(); + int rows = 0; + while (reader.Read()) + rows++; + return rows; + } + + [Benchmark] + public int ReadWithComments() + { + using var reader = Open(); + int comments = 0; + while (reader.Read()) + { + for (int column = 0; column < reader.FieldCount; column++) + comments += reader.GetComment(column)?.Messages.Count ?? 0; + } + + return comments; + } + + [Benchmark] + public CellCommentThread? OpenAndFirstLookup() + { + using var reader = Open(); + reader.Read(); + if (HasComments) + reader.Read(); + return reader.GetComment(_column); + } + + [Benchmark(OperationsPerInvoke = 1000)] + public int CachedLookup() + { + int messages = 0; + for (int i = 0; i < 1000; i++) + messages += _cachedReader.GetComment(_column)?.Messages.Count ?? 0; + return messages; + } + + private IExcelDataReader Open() => ExcelReaderFactory.CreateReader(new MemoryStream(_data, writable: false)); +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/CellMaterialization.cs b/src/ExcelDataReader.Benchmarks/CellMaterialization.cs new file mode 100644 index 00000000..14819042 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/CellMaterialization.cs @@ -0,0 +1,61 @@ +using System.Linq.Expressions; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class CellMaterialization +{ + private Func _materialize = null!; + + [Params("Number", "Boolean", "Date", "Duration", "OneCondition", "TwoConditions")] + public string Values { get; set; } = string.Empty; + + [GlobalSetup] + public void Setup() + { + var assembly = typeof(ExcelReaderFactory).Assembly; + var workbookType = assembly.GetType("ExcelDataReader.Core.CommonWorkbook")!; + var decodedType = assembly.GetType("ExcelDataReader.Core.DecodedCellValue")!; + var kindType = assembly.GetType("ExcelDataReader.Core.CellValueKind")!; + var styleType = assembly.GetType("ExcelDataReader.Core.ExtendedFormat")!; + var workbook = Activator.CreateInstance(workbookType)!; + int format = Values switch { "Date" => 14, "Duration" => 46, "OneCondition" or "TwoConditions" => 164, _ => 0 }; + if (Values is "OneCondition" or "TwoConditions") + { + string formatString = Values == "OneCondition" ? "[>0]yyyy;0" : "[>0]yyyy;[<-1]0;[h]:mm"; + workbookType.GetMethod("AddNumberFormat")!.Invoke(workbook, [format, formatString]); + } + + var style = Activator.CreateInstance(styleType, [format])!; + var number = Expression.Parameter(typeof(double), "value"); + Expression value = Values == "Boolean" ? Expression.NotEqual(number, Expression.Constant(0D)) : number; + var constructor = decodedType.GetConstructor([value.Type]); + var decoded = constructor != null + ? Expression.New(constructor, value) + : Expression.New( + decodedType.GetConstructor([typeof(object), kindType, typeof(uint)])!, + Expression.Convert(value, typeof(object)), + Expression.Constant(Enum.ToObject(kindType, 0), kindType), + Expression.Constant(0U)); + var create = workbookType.GetMethod("CreateCell")!; + var cell = Expression.Call( + Expression.Constant(workbook), + create, + Expression.Constant(0), + decoded, + Expression.Constant(style), + Expression.Constant(null, create.GetParameters()[3].ParameterType), + Expression.Constant(false)); + _materialize = Expression.Lambda>(Expression.Property(cell, "Value"), number).Compile(); + } + + [Benchmark(OperationsPerInvoke = 1024)] + public object ConvertCells() + { + object result = null!; + for (int i = 0; i < 1024; i++) + result = _materialize(i & 1); + return result; + } +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/CsvRuns.cs b/src/ExcelDataReader.Benchmarks/CsvRuns.cs new file mode 100644 index 00000000..d65b4e0b --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/CsvRuns.cs @@ -0,0 +1,67 @@ +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class CsvRuns +{ + private byte[] _data = []; + private ExcelReaderConfiguration _configuration = null!; + + [Params("short", "long", "quoted", "escaped", "trimmed")] + public string Content { get; set; } = string.Empty; + + [Params(false, true)] + public bool DetectSeparator { get; set; } + + [Params(",", "||")] + public string Separator { get; set; } = ","; + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + string field = Content switch + { + "long" => new string('x', 1024), + "quoted" => "\"" + new string('x', 1024) + ",\r\nend\"", + "escaped" => "\"a\"\"b\"\"c\"", + "trimmed" => " alpha ", + _ => "alpha", + }; + var text = new StringBuilder(); + for (int row = 0; row < 1000; row++) + text.Append(field).Append(Separator).Append(field).Append(Separator).Append(field).Append("\r\n"); + _data = Encoding.UTF8.GetBytes(text.ToString()); + _configuration = new ExcelReaderConfiguration + { + AutodetectSeparators = DetectSeparator ? [",", ";", "\t", Separator == "," ? "|" : Separator, "#"] : [Separator], + }; + + int decodedLength = Content switch + { + "long" => 1024, + "quoted" => 1030, + _ => 5, + }; + if (Read() != 1000L * (1 + 3 * decodedLength)) + throw new InvalidOperationException("CSV benchmark checksum mismatch."); + } + + [Benchmark] + public long Read() + { + using var stream = new MemoryStream(_data, false); + using var reader = ExcelReaderFactory.CreateCsvReader(stream, _configuration); + long checksum = 0; + while (reader.Read()) + { + checksum++; + for (int column = 0; column < reader.FieldCount; column++) + checksum += reader.GetString(column).Length; + } + + return checksum; + } +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/CustomNumberFormats.cs b/src/ExcelDataReader.Benchmarks/CustomNumberFormats.cs new file mode 100644 index 00000000..c5985288 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/CustomNumberFormats.cs @@ -0,0 +1,51 @@ +using BenchmarkDotNet.Attributes; +#if NET8_0_OR_GREATER +using System.Collections.Frozen; +#endif + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class CustomNumberFormats +{ + private Dictionary _dictionary = null!; + private int[] _indices = []; +#if NET8_0_OR_GREATER + private FrozenDictionary _frozen = null!; +#endif + + [Params(0, 1, 16, 256)] + public int Count { get; set; } + + [GlobalSetup] + public void Setup() + { + _dictionary = []; + for (int i = 0; i < Count; i++) + _dictionary.Add(164 + i, new object()); +#if NET8_0_OR_GREATER + _frozen = _dictionary.ToFrozenDictionary(); +#endif + _indices = Enumerable.Range(0, 1024).Select(i => i % 2 == 0 ? i % 82 : 164 + i % Math.Max(1, Count)).ToArray(); + } + + [Benchmark(Baseline = true, OperationsPerInvoke = 1024)] + public int DictionaryLookup() + { + int count = 0; + foreach (int index in _indices) + count += _dictionary.TryGetValue(index, out _) ? 1 : 0; + return count; + } + +#if NET8_0_OR_GREATER + [Benchmark(OperationsPerInvoke = 1024)] + public int FrozenLookup() + { + int count = 0; + foreach (int index in _indices) + count += _frozen.TryGetValue(index, out _) ? 1 : 0; + return count; + } +#endif +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/DataSetConversion.cs b/src/ExcelDataReader.Benchmarks/DataSetConversion.cs new file mode 100644 index 00000000..bf6dd235 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/DataSetConversion.cs @@ -0,0 +1,57 @@ +using System.Data; +using System.Globalization; +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class DataSetConversion +{ + private byte[] _data = []; + + [Params(false, true)] + public bool FillMergedCells { get; set; } + + [Params(false, true)] + public bool UseColumnDataType { get; set; } + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + var xml = new StringBuilder(""" + + + """); + for (int row = 0; row < 2000; row++) + { + xml.Append(""); + for (int column = 0; column < 10; column++) + { + xml.Append(column == 0 && FillMergedCells ? "" : ""); + xml.Append(""); + xml.Append((row * 10 + column).ToString(CultureInfo.InvariantCulture)); + xml.Append(""); + if (column == 0 && FillMergedCells) + column = 4; + } + + xml.Append(""); + } + + xml.Append("
"); + _data = Encoding.UTF8.GetBytes(xml.ToString()); + } + + [Benchmark] + public DataSet Convert() + { + using var reader = ExcelReaderFactory.CreateReader(new MemoryStream(_data, writable: false)); + return reader.AsDataSet(new ExcelDataSetConfiguration + { + UseColumnDataType = UseColumnDataType, + ConfigureDataTable = _ => new ExcelDataTableConfiguration { FillMergedCellsValue = FillMergedCells }, + }); + } +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/ExcelDataReader.Benchmarks.csproj b/src/ExcelDataReader.Benchmarks/ExcelDataReader.Benchmarks.csproj index 1b67a3d7..2bb655af 100644 --- a/src/ExcelDataReader.Benchmarks/ExcelDataReader.Benchmarks.csproj +++ b/src/ExcelDataReader.Benchmarks/ExcelDataReader.Benchmarks.csproj @@ -1,6 +1,7 @@  - net8.0 + net10.0 + $(TargetFrameworks);net462 Exe @@ -14,15 +15,41 @@ false - + + + + + + + + + - - - - + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/OpenXmlFile.cs b/src/ExcelDataReader.Benchmarks/OpenXmlFile.cs index 8899abc4..12ed11cc 100644 --- a/src/ExcelDataReader.Benchmarks/OpenXmlFile.cs +++ b/src/ExcelDataReader.Benchmarks/OpenXmlFile.cs @@ -15,21 +15,21 @@ public void Setup() [Benchmark] public bool OpenSingleFileXslx() { - using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.Test10x10000.xlsx")); + using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xlsx")); return reader.Read(); } [Benchmark] public bool OpenSingleFileXslb() { - using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.Test10x10000.xlsb")); + using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xlsb")); return reader.Read(); } [Benchmark] public bool OpenSingleFileXls() { - using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.Test10x10000.xls")); + using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xls")); return reader.Read(); } } diff --git a/src/ExcelDataReader.Benchmarks/OpenXmlOrdering.cs b/src/ExcelDataReader.Benchmarks/OpenXmlOrdering.cs new file mode 100644 index 00000000..11b31937 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/OpenXmlOrdering.cs @@ -0,0 +1,122 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class OpenXmlOrdering +{ + private byte[] _data = []; + + [Params("xlsx", "xlsb")] + public string Format { get; set; } = string.Empty; + + [Params("Ordered", "Overlap", "CrossBlock", "Sparse", "SparseOrdered", "Fragments", "Reverse")] + public string Order { get; set; } = string.Empty; + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + int[] rows = [.. Enumerable.Range(0, 10000)]; + if (Order == "Overlap") + { + for (int i = 0; i < rows.Length; i += 100) + (rows[i], rows[i + 1]) = (rows[i + 1], rows[i]); + } + else if (Order == "CrossBlock") + { + (rows[0], rows[64]) = (rows[64], rows[0]); + } + else if (Order is "Sparse" or "SparseOrdered") + { + rows = [.. rows.Select(row => row * 3)]; + if (Order == "Sparse") + (rows[0], rows[64]) = (rows[64], rows[0]); + } + else if (Order == "Fragments") + { + rows = [.. rows.SelectMany(row => Enumerable.Repeat(row, 20))]; + } + else if (Order == "Reverse") + { + Array.Reverse(rows); + } + + using var source = typeof(OpenXmlOrdering).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000." + Format)!; + using var buffer = new MemoryStream(); + source.CopyTo(buffer); + using (var archive = new ZipArchive(buffer, ZipArchiveMode.Update, leaveOpen: true)) + { + string suffix = Format == "xlsx" ? ".xml" : ".bin"; + var entry = archive.Entries.First(item => item.FullName.StartsWith("xl/worksheets/", StringComparison.Ordinal) && item.FullName.EndsWith(suffix, StringComparison.Ordinal)); + string name = entry.FullName; + entry.Delete(); + using var stream = archive.CreateEntry(name).Open(); + if (Format == "xlsx") + { + using var writer = new StreamWriter(stream, new UTF8Encoding(false)); + writer.Write(""); + foreach (int row in rows) + { + writer.Write(""); + writer.Write((row + 0.25).ToString(CultureInfo.InvariantCulture)); + writer.Write(""); + } + + writer.Write(""); + } + else + { + using var writer = new BinaryWriter(stream); + writer.Write(new byte[] { 0x91, 1, 0 }); + foreach (int row in rows) + { + writer.Write((byte)0); + writer.Write((byte)12); + writer.Write(row); + writer.Write(0); + writer.Write((ushort)300); + writer.Write((byte)0); + writer.Write((byte)0b100000); + writer.Write((byte)5); + writer.Write((byte)16); + writer.Write(0); + writer.Write(0); + writer.Write(row + 0.25); + } + + writer.Write(new byte[] { 0x92, 1, 0 }); + } + } + + _data = buffer.ToArray(); + if (Read() != rows.Distinct().Sum(row => row + 0.25)) + throw new InvalidOperationException("The ordering benchmark did not return the expected cell values."); + } + + [Benchmark] + public int Open() + { + using var reader = ExcelReaderFactory.CreateReader(new MemoryStream(_data, writable: false)); + return reader.RowCount; + } + + [Benchmark] + public double Read() + { + using var reader = ExcelReaderFactory.CreateReader(new MemoryStream(_data, writable: false)); + double checksum = 0; + while (reader.Read()) + { + if (!reader.IsDBNull(0)) + checksum += reader.GetDouble(0); + } + + return checksum; + } +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/ParseCustomFormats.cs b/src/ExcelDataReader.Benchmarks/ParseCustomFormats.cs new file mode 100644 index 00000000..d9c13bb8 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/ParseCustomFormats.cs @@ -0,0 +1,14 @@ +using BenchmarkDotNet.Attributes; +using ExcelDataReader.Core.NumberFormat; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class ParseCustomFormats +{ + [Params("0", "0.00", "#,##0.00;[Red]-#,##0.00", "[>=100]0.00;[Blue][h]:mm:ss", "yyyy-mm-dd hh:mm:ss.000", "0.00E+00", "0.00e-00", "# ?/?")] + public string Format { get; set; } = string.Empty; + + [Benchmark] + public NumberFormatString Parse() => new(Format); +} diff --git a/src/ExcelDataReader.Benchmarks/ParseLongFormats.cs b/src/ExcelDataReader.Benchmarks/ParseLongFormats.cs new file mode 100644 index 00000000..856bd511 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/ParseLongFormats.cs @@ -0,0 +1,29 @@ +using BenchmarkDotNet.Attributes; +using ExcelDataReader.Core.NumberFormat; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class ParseLongFormats +{ + private string _format = string.Empty; + + [Params("Digits", "Dates", "Directives", "Unicode")] + public string Content { get; set; } = string.Empty; + + [GlobalSetup] + public void Setup() + { + _format = Content switch + { + "Digits" => new string('0', 1024) + ".00", + "Dates" => string.Concat(Enumerable.Repeat("yyyy-mm-dd hh:mm:ss.000 ", 32)), + "Directives" => string.Concat(Enumerable.Repeat("[>=100][Red]", 64)) + "0.00", + "Unicode" => string.Concat(Enumerable.Repeat("yyyy\"\u5E74\"m\"\u6708\"d\"\u65E5\"", 32)), + _ => throw new InvalidOperationException(Content), + }; + } + + [Benchmark] + public NumberFormatString Parse() => new(_format); +} diff --git a/src/ExcelDataReader.Benchmarks/PerCellRead.cs b/src/ExcelDataReader.Benchmarks/PerCellRead.cs new file mode 100644 index 00000000..08ba8a85 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/PerCellRead.cs @@ -0,0 +1,179 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; +using BenchmarkDotNet.Attributes; +using ExcelDataReader.TestFixtures; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class PerCellRead +{ + private byte[] _data = []; + + [Params("Number", "Fraction", "Boolean", "Date", "Duration", "Text")] + public string Values { get; set; } = string.Empty; + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + using var buffer = new MemoryStream(); + var template = AllocationTestWorkbook.CreateXlsx([], false); + buffer.Write(template, 0, template.Length); + using (var archive = new ZipArchive(buffer, ZipArchiveMode.Update, leaveOpen: true)) + { + archive.GetEntry("xl/_rels/workbook.xml.rels")!.Delete(); + using (var relationships = new StreamWriter(archive.CreateEntry("xl/_rels/workbook.xml.rels").Open())) + relationships.Write(""); + archive.GetEntry("xl/worksheets/sheet1.xml")!.Delete(); + using (var writer = new StreamWriter(archive.CreateEntry("xl/worksheets/sheet1.xml").Open())) + { + writer.Write(""); + for (int row = 1; row <= 10000; row++) + { + string index = row.ToString(CultureInfo.InvariantCulture); + writer.Write(""); + for (int column = 0; column < 10; column++) + { + string reference = ((char)('A' + column)).ToString() + index; + string attributes = Values switch + { + "Boolean" => " t=\"b\"", + "Date" => " s=\"1\"", + "Duration" => " s=\"2\"", + "Text" => " t=\"str\"", + _ => string.Empty, + }; + string value = Values switch + { + "Boolean" => (row + column) % 2 == 0 ? "1" : "0", + "Text" => "alpha", + "Fraction" => index + ".5", + _ => index, + }; + writer.Write("" + value + ""); + } + + writer.Write(""); + } + + writer.Write(""); + } + + using var styles = new StreamWriter(archive.CreateEntry("xl/styles.xml").Open()); + styles.Write(""); + } + + _data = buffer.ToArray(); + long expected = Values switch + { + "Boolean" => 50000, + "Text" => 500000, + "Date" => 100000, + "Duration" => 500050000, + _ => 500050000, + }; + if (Read() != expected) + throw new InvalidOperationException("Unexpected cell values."); + if (ReadTyped() != expected || ReadOnly() != 10000) + throw new InvalidOperationException("Unexpected typed cell values or row count."); + } + + [Benchmark] + public long Read() + { + using var stream = new MemoryStream(_data, writable: false); + using var reader = ExcelReaderFactory.CreateReader(stream); + long checksum = 0; + while (reader.Read()) + { + for (int column = 0; column < reader.FieldCount; column++) + { + checksum += reader.GetValue(column) switch + { + double value when Values is "Number" or "Fraction" => (long)value, + bool value when Values == "Boolean" => value ? 1 : 0, + DateTime when Values == "Date" => 1, + TimeSpan value when Values == "Duration" => (long)value.TotalDays, + string value when Values == "Text" => value.Length, + _ => throw new InvalidOperationException("Unexpected cell type."), + }; + } + } + + return checksum; + } + + [Benchmark] + public int ReadOnly() + { + using var stream = new MemoryStream(_data, writable: false); + using var reader = ExcelReaderFactory.CreateReader(stream); + int rows = 0; + while (reader.Read()) + rows++; + return rows; + } + + [Benchmark] + public long ReadTyped() + { + using var stream = new MemoryStream(_data, writable: false); + using var reader = ExcelReaderFactory.CreateReader(stream); + long checksum = 0; + while (reader.Read()) + { + for (int column = 0; column < reader.FieldCount; column++) + { + checksum += Values switch + { + "Number" or "Fraction" => (long)reader.GetDouble(column), + "Boolean" => reader.GetBoolean(column) ? 1 : 0, + "Date" => reader.GetDateTime(column).Year > 0 ? 1 : 0, + "Duration" => (long)((TimeSpan)reader.GetValue(column)).TotalDays, + "Text" => reader.GetString(column).Length, + _ => throw new InvalidOperationException("Unexpected cell type."), + }; + } + } + + return checksum; + } + + [Benchmark] + public long ReadRepeatedValues() + { + using var stream = new MemoryStream(_data, writable: false); + using var reader = ExcelReaderFactory.CreateReader(stream); + long checksum = 0; + while (reader.Read()) + { + for (int column = 0; column < reader.FieldCount; column++) + { + var first = reader.GetValue(column); + var second = reader.GetValue(column); + if (!Equals(first, second)) + throw new InvalidOperationException("Cell value changed between accesses."); + checksum++; + } + } + + return checksum; + } + + [Benchmark] + public int ReadStyles() + { + using var stream = new MemoryStream(_data, writable: false); + using var reader = ExcelReaderFactory.CreateReader(stream); + int checksum = 0; + while (reader.Read()) + { + for (int column = 0; column < reader.FieldCount; column++) + checksum += reader.GetCellStyle(column).NumberFormatIndex; + } + + return checksum; + } +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/Program.cs b/src/ExcelDataReader.Benchmarks/Program.cs index 46cb71f0..5884a87f 100644 --- a/src/ExcelDataReader.Benchmarks/Program.cs +++ b/src/ExcelDataReader.Benchmarks/Program.cs @@ -1,3 +1,9 @@ using BenchmarkDotNet.Running; +using ExcelDataReader.Benchmarks; -BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); \ No newline at end of file +if (args.Length > 0 && args[0] == "--sst-io") + SharedStringIo.Run(); +else if (args.Length > 0 && args[0] is "--sst-generate" or "--sst-memory") + SharedStringStorage.RunScenario(args); +else + BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); diff --git a/src/ExcelDataReader.Benchmarks/README.md b/src/ExcelDataReader.Benchmarks/README.md new file mode 100644 index 00000000..ce4e8a8e --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/README.md @@ -0,0 +1,65 @@ +# Allocation benchmarks + +`ReadTextFragments` covers single-fragment and rich XLSX strings, SpreadsheetML +Data text, and OOXML escapes. `ParseCustomFormats` covers custom number-format +parsing, including simple decimals, conditions, dates, exponentials, and fractions. +Both use `MemoryDiagnoser`; workbook generation happens in `GlobalSetup`, +outside the measured operation. Existing `ReadAllStrings`, `ReadRealWorldFiles`, +and `SinglePassRead` benchmarks provide whole-file comparisons. + +`SharedStringStorage` compares Default, below-threshold SpillToDisk, and disk-spilled SST +storage using generated million-entry workbooks. See [shared string storage +details and benchmarks](SharedStringStorage.md) for measured memory/throughput +tradeoffs, corpus generation, and reproduction commands. + +`SharedStringConstruction` measures reader creation/disposal without traversal +for the workbook selected by `EDR_SST_INPUT`. Optional `EDR_SST_LIBRARY` selects +a preserved baseline library DLL. See the storage document for reproduction +commands and storage tradeoffs. + +`SharedStringTraversal` compares Default, SpillToDisk1 (1 MiB), and SpillToDisk256 (256 MiB) over the existing workbook +selected by `EDR_SST_INPUT`, including reader creation, complete traversal, +checksum validation and disposal with SinglePassMode enabled. It is intended +to expose decoding/repeated-reference costs that construction-only timings miss. +For the supplied 100k/one-million-entry corpora, SpillToDisk1 forces spill and SpillToDisk256 +stays below threshold. Confirm spill with `--sst-memory`; its forced-GC +checkpoints measure retention, not throughput. + +`SectorChain` compares the original list search, the library's current +Floyd cycle detection, a hybrid list/hash set, a hash set, and a bitset. It measures +synthetic contiguous, fragmented and sparse chains alongside workbook stream +chains from three XLS fixtures. Setup validates the results and cycle detection +outside the measured operation. For example, run the .NET Framework benchmarks: + +```powershell +dotnet run --project src\ExcelDataReader.Benchmarks\ExcelDataReader.Benchmarks.csproj -c Release -f net462 -- --filter "*SectorChain*" --job short +``` + +`--sst-io` diagnoses injected MemoryStream/FileStream construction and lookup +calls over sequential, reverse-like, random, and hot Unicode references. +It runs three warmups and five measured repetitions; counts are managed-stream +calls, not OS I/O. Timing includes output validation and is diagnostic rather +than a replacement for whole-read BenchmarkDotNet results. + +`ParseLongFormats` covers long digit/date patterns, repeated bracket directives, +and quoted Unicode text. The format parser stores temporary source ranges rather +than token strings and only produces validity/date/duration classification. +Modern targets validate numeric slices with spans; older targets retain numeric +string fallbacks where the corresponding span APIs are unavailable. + +Run the allocation benchmarks on net10.0: + +```powershell +dotnet run --project src\ExcelDataReader.Benchmarks\ExcelDataReader.Benchmarks.csproj -c Release -f net10.0 -- --filter "*ReadTextFragments*" "*ParseCustomFormats*" "*ParseLongFormats*" --exporters json +``` + +The net10.0 host uses the library's net10.0 build through normal project-reference +selection. The library continues to support net462, netstandard2.0, +netstandard2.1, and net10.0, with optimized paths gated by API availability. + +Run builds, tests, and benchmarks serially: they share output directories. Capture +unchanged-code and candidate results in separate artifact directories on the same +machine with the same runtime and library target. Use warmed, repeated +measurements, not a `Dry` job, to assess throughput. Keep an allocation optimization +only when it reduces allocations without a statistically meaningful slowdown, +including multipart text and ordinary strings. diff --git a/src/ExcelDataReader.Benchmarks/ReadAllStrings.cs b/src/ExcelDataReader.Benchmarks/ReadAllStrings.cs new file mode 100644 index 00000000..54f8c88e --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/ReadAllStrings.cs @@ -0,0 +1,56 @@ +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +/// +/// Benchmarks for reading all string cell values, exercising SST lookup performance. +/// For XLS, this validates the lazy string cache (issue #525): strings are decoded and cached +/// on first access in GetString(), releasing the raw byte[] backing after the first lookup. +/// Repeated access of the same SST index returns the cached string with zero allocation. +/// +[MemoryDiagnoser] +public class ReadAllStrings +{ + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + } + + [Benchmark] + public string ReadAllStringsXlsx() + { + return ReadStrings(ExcelReaderFactory.CreateReader( + typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xlsx"))); + } + + [Benchmark] + public string ReadAllStringsXlsb() + { + return ReadStrings(ExcelReaderFactory.CreateReader( + typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xlsb"))); + } + + [Benchmark] + public string ReadAllStringsXls() + { + return ReadStrings(ExcelReaderFactory.CreateReader( + typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xls"))); + } + + private static string ReadStrings(IExcelDataReader reader) + { + using (reader) + { + string last = null; + while (reader.Read()) + { + for (var i = 0; i < reader.FieldCount; i++) + last = reader.GetString(i); + } + + return last; + } + } +} diff --git a/src/ExcelDataReader.Benchmarks/ReadEncrypted.cs b/src/ExcelDataReader.Benchmarks/ReadEncrypted.cs index 4f795a5a..0daa87e5 100644 --- a/src/ExcelDataReader.Benchmarks/ReadEncrypted.cs +++ b/src/ExcelDataReader.Benchmarks/ReadEncrypted.cs @@ -15,7 +15,7 @@ public void Setup() [Benchmark] public void Xlsx() { - using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.Test_git_issue289.xlsx")); + using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.Issue289.xlsx")); Read(reader); } diff --git a/src/ExcelDataReader.Benchmarks/ReadEncryptedFiles.cs b/src/ExcelDataReader.Benchmarks/ReadEncryptedFiles.cs new file mode 100644 index 00000000..a521b668 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/ReadEncryptedFiles.cs @@ -0,0 +1,58 @@ +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class ReadEncryptedFiles +{ + private byte[] _data = []; + private ExcelReaderConfiguration _configuration; + + [Params( + "agile_AES128_SHA1_CBC_pwd_password.xlsx", + "standard_AES128_SHA1_ECB_pwd_password.xlsx", + "Issue242_StdRc4PwdPassword.xls", + "Issue242_XorPwdPassword.xls")] + public string File { get; set; } = string.Empty; + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + + using var resource = typeof(ReadEncryptedFiles).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks." + File) + ?? throw new InvalidOperationException("Missing embedded resource " + File); + using var buffer = new MemoryStream(); + resource.CopyTo(buffer); + _data = buffer.ToArray(); + _configuration = new ExcelReaderConfiguration { Password = "password" }; + } + + [Benchmark] + public void OpenReader() + { + using var reader = ExcelReaderFactory.CreateReader(new MemoryStream(_data, writable: false), _configuration); + } + + [Benchmark] + public int ReadAllValues() + { + using var reader = ExcelReaderFactory.CreateReader(new MemoryStream(_data, writable: false), _configuration); + var nonNull = 0; + do + { + while (reader.Read()) + { + for (var i = 0; i < reader.FieldCount; i++) + { + if (reader.GetValue(i) != null) + nonNull++; + } + } + } + while (reader.NextResult()); + + return nonNull; + } +} diff --git a/src/ExcelDataReader.Benchmarks/ReadRealWorldFiles.cs b/src/ExcelDataReader.Benchmarks/ReadRealWorldFiles.cs new file mode 100644 index 00000000..709237c9 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/ReadRealWorldFiles.cs @@ -0,0 +1,70 @@ +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +/// +/// Reads every value in all sheets of real-world test workbooks with mixed content +/// (numbers, dates, formulas, inline and shared strings, blanks). +/// +[MemoryDiagnoser] +public class ReadRealWorldFiles +{ + private byte[] _data = []; + + private ExcelReaderConfiguration _configuration; + + [Params( + "BigFormatted.xls", + "BigFormatted.xlsx", + "Issue263.xls", + "OldIssue11572_CodePage.xls", + "Issue173.xls", + "InvalidByteOrderValueInHeader.xls", + "LotsOfSheets.xls", + "LotsOfSheets.xlsx", + "LotsOfSheets.xlsb", + "agile_AES128_SHA1_CBC_pwd_password.xlsx", + "standard_AES128_SHA1_ECB_pwd_password.xlsx", + "Issue242_StdRc4PwdPassword.xls", + "Issue242_XorPwdPassword.xls")] + public string File { get; set; } = string.Empty; + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + + using var resource = typeof(ReadRealWorldFiles).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks." + File) + ?? throw new InvalidOperationException("Missing embedded resource " + File); + using var buffer = new MemoryStream(); + resource.CopyTo(buffer); + _data = buffer.ToArray(); + + // Encrypted test workbooks all use the password "password". + _configuration = File.IndexOf("pwd", StringComparison.OrdinalIgnoreCase) >= 0 + ? new ExcelReaderConfiguration { Password = "password" } + : null; + } + + [Benchmark] + public int ReadAllValues() + { + using var reader = ExcelReaderFactory.CreateReader(new MemoryStream(_data, writable: false), _configuration); + var nonNull = 0; + do + { + while (reader.Read()) + { + for (var i = 0; i < reader.FieldCount; i++) + { + if (reader.GetValue(i) != null) + nonNull++; + } + } + } + while (reader.NextResult()); + + return nonNull; + } +} diff --git a/src/ExcelDataReader.Benchmarks/ReadTextFragments.cs b/src/ExcelDataReader.Benchmarks/ReadTextFragments.cs new file mode 100644 index 00000000..9ae24058 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/ReadTextFragments.cs @@ -0,0 +1,44 @@ +using System.Text; +using BenchmarkDotNet.Attributes; +using ExcelDataReader.TestFixtures; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class ReadTextFragments +{ + private byte[] _data = []; + + [Params("InlineSingle", "InlineRich", "SharedSingle", "SharedRich", "XmlSingle", "XmlFragments", "EscapeOrdinary", "EscapeValid", "EscapeInvalid", "EscapeLong")] + public string Content { get; set; } = string.Empty; + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + string fragment = Content switch + { + "InlineRich" or "SharedRich" => "first second", + "XmlSingle" => "first second", + "XmlFragments" => "first third", + "EscapeValid" => "first_x000A_second_x0041__x005F_x0041_", + "EscapeInvalid" => "first_x00af_second_xG000_third_x004", + "EscapeLong" => "" + new string('a', 4096) + "_x000A_" + new string('b', 4096) + "", + _ => "first second", + }; + var items = Enumerable.Repeat(fragment, 1000).ToArray(); + _data = Content.StartsWith("Xml", StringComparison.Ordinal) + ? AllocationTestWorkbook.CreateSpreadsheetXml(items) + : AllocationTestWorkbook.CreateXlsx(items, Content.StartsWith("Shared", StringComparison.Ordinal)); + } + + [Benchmark] + public int ReadValues() + { + using var reader = ExcelReaderFactory.CreateReader(new MemoryStream(_data, writable: false)); + int length = 0; + while (reader.Read()) + length += reader.GetString(0)?.Length ?? 0; + return length; + } +} diff --git a/src/ExcelDataReader.Benchmarks/ReadXmlFile.cs b/src/ExcelDataReader.Benchmarks/ReadXmlFile.cs index 903a5406..141cf5ad 100644 --- a/src/ExcelDataReader.Benchmarks/ReadXmlFile.cs +++ b/src/ExcelDataReader.Benchmarks/ReadXmlFile.cs @@ -15,21 +15,21 @@ public void Setup() [Benchmark] public void ReadSingleFileXslx() { - using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.Test10x10000.xlsx")); + using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xlsx")); Read(reader); } [Benchmark] public void ReadSingleFileXslb() { - using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.Test10x10000.xlsb")); + using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xlsb")); Read(reader); } [Benchmark] public void ReadSingleFileXls() { - using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.Test10x10000.xls")); + using var reader = ExcelReaderFactory.CreateReader(typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xls")); Read(reader); } diff --git a/src/ExcelDataReader.Benchmarks/ReferenceParsing.cs b/src/ExcelDataReader.Benchmarks/ReferenceParsing.cs new file mode 100644 index 00000000..f49b8641 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/ReferenceParsing.cs @@ -0,0 +1,51 @@ +using System.Globalization; +using System.Reflection; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class ReferenceParsing +{ + private string[] _references = []; + private ParseReference _parse = null!; + +#if NET8_0_OR_GREATER + private delegate bool ParseReference(ReadOnlySpan value, out int column, out int row); +#else + private delegate bool ParseReference(string value, out int column, out int row); +#endif + + [Params("Uppercase", "Lowercase", "Invalid")] + public string Input { get; set; } = string.Empty; + + [GlobalSetup] + public void Setup() + { + var method = typeof(ExcelReaderFactory).Assembly.GetType("ExcelDataReader.Core.ReferenceHelper")! + .GetMethod("ParseReference", BindingFlags.Public | BindingFlags.Static)!; + _parse = (ParseReference)Delegate.CreateDelegate(typeof(ParseReference), method); + string[] columns = Input switch + { + "Uppercase" => ["A", "J", "AZ", "XFD"], + "Lowercase" => ["a", "j", "az", "xfd"], + _ => [string.Empty, "$A", "A!", "AZ"], + }; + _references = Enumerable.Range(0, 1024) + .Select(i => columns[i % columns.Length] + (i + 1).ToString(CultureInfo.InvariantCulture) + (Input == "Invalid" ? "!" : string.Empty)) + .ToArray(); + } + + [Benchmark(OperationsPerInvoke = 1024)] + public int Parse() + { + int result = 0; + foreach (string reference in _references) + { + if (_parse(reference, out int column, out int row)) + result += column + row; + } + + return result; + } +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/RepeatedSharedStrings.cs b/src/ExcelDataReader.Benchmarks/RepeatedSharedStrings.cs new file mode 100644 index 00000000..52ed6aa6 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/RepeatedSharedStrings.cs @@ -0,0 +1,168 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; +using BenchmarkDotNet.Attributes; +using ExcelDataReader.TestFixtures; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class RepeatedSharedStrings +{ + private byte[] _data = []; + private string _expected = string.Empty; + + [Params("xlsx", "xlsb")] + public string Format { get; set; } = string.Empty; + + [Params("Ordinary", "Escaped", "Invalid")] + public string Content { get; set; } = string.Empty; + + [Params("Repeated", "Unique")] + public string Pattern { get; set; } = string.Empty; + + [Params(SharedStringStorageMode.Default, SharedStringStorageMode.SpillToDisk)] + public SharedStringStorageMode Storage { get; set; } + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + string text = Content switch + { + "Escaped" => "first_x000A_second_x005F_x0041_", + "Invalid" => "first_x00af_second_xG000_", + _ => "first second ordinary string", + }; + _expected = Content == "Escaped" ? "first\nsecond_x0041_" : text; + if (Format == "xlsx") + { + using var buffer = new MemoryStream(); + var items = Enumerable.Repeat("" + text + "", Pattern == "Unique" ? 20000 : 1).ToList(); + if (Storage == SharedStringStorageMode.SpillToDisk) + items.Add("" + new string('p', 600000) + ""); + byte[] template = AllocationTestWorkbook.CreateXlsx(items.ToArray(), true); + buffer.Write(template, 0, template.Length); + using (var archive = new ZipArchive(buffer, ZipArchiveMode.Update, leaveOpen: true)) + { + archive.GetEntry("xl/worksheets/sheet1.xml")!.Delete(); + using var writer = new StreamWriter(archive.CreateEntry("xl/worksheets/sheet1.xml").Open()); + writer.Write(""); + for (int row = 1; row <= 20000; row++) + { + string index = row.ToString(CultureInfo.InvariantCulture); + string reference = (Pattern == "Unique" ? row - 1 : 0).ToString(CultureInfo.InvariantCulture); + writer.Write("" + reference + ""); + } + + writer.Write(""); + } + + _data = buffer.ToArray(); + } + else + { + string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".xlsb"); + try + { + SharedStringWorkbook.Create(path, "xlsb", 20000, 64); + using (var archive = ZipFile.Open(path, ZipArchiveMode.Update)) + { + archive.GetEntry("xl/sharedStrings.bin")!.Delete(); + using (var writer = new BinaryWriter(archive.CreateEntry("xl/sharedStrings.bin").Open())) + { + for (int i = 0; i < (Pattern == "Unique" ? 20000 : 1); i++) + { + byte[] bytes = Encoding.Unicode.GetBytes(text); + writer.Write((byte)0x13); + writer.Write((byte)(5 + bytes.Length)); + writer.Write((byte)0); + writer.Write(text.Length); + writer.Write(bytes); + } + + if (Storage == SharedStringStorageMode.SpillToDisk) + { + var padding = new byte[5 + 1200000]; + BitConverter.GetBytes(600000).CopyTo(padding, 1); + WriteRecord(writer, 0x13, padding); + } + } + + archive.GetEntry("xl/worksheets/sheet1.bin")!.Delete(); + using var sheet = new BinaryWriter(archive.CreateEntry("xl/worksheets/sheet1.bin").Open()); + WriteRecord(sheet, 0x81, []); + WriteRecord(sheet, 0x91, []); + for (int row = 0; row < 5000; row++) + { + var header = new byte[17]; + BitConverter.GetBytes(row).CopyTo(header, 0); + WriteRecord(sheet, 0, header); + for (int column = 0; column < 4; column++) + { + var cell = new byte[12]; + BitConverter.GetBytes(column).CopyTo(cell, 0); + BitConverter.GetBytes(Pattern == "Unique" ? row * 4 + column : 0).CopyTo(cell, 8); + WriteRecord(sheet, 7, cell); + } + } + + WriteRecord(sheet, 0x92, []); + WriteRecord(sheet, 0x82, []); + } + + _data = File.ReadAllBytes(path); + } + finally + { + File.Delete(path); + } + } + + if (Read() != 20000L * _expected.Length) + throw new InvalidOperationException("Shared string output changed."); + } + + [Benchmark] + public long Read() + { + using var reader = ExcelReaderFactory.CreateReader( + new MemoryStream(_data, writable: false), + new ExcelReaderConfiguration { SharedStringStorageMode = Storage, SharedStringSpillThreshold = 1024 * 1024 }); + long length = 0; + while (reader.Read()) + { + for (int column = 0; column < reader.FieldCount; column++) + { + string value = reader.GetString(column); + if (value != _expected) + throw new InvalidOperationException("Shared string output changed."); + length += value.Length; + } + } + + return length; + } + + private static void WriteRecord(BinaryWriter writer, int id, byte[] data) + { + if (id >= 128) + { + writer.Write((byte)((id & 127) | 128)); + writer.Write((byte)(id >> 7)); + } + else + { + writer.Write((byte)id); + } + + int length = data.Length; + do + { + writer.Write((byte)((length & 127) | (length > 127 ? 128 : 0))); + length >>= 7; + } + while (length != 0); + writer.Write(data); + } +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/SectorChain.cs b/src/ExcelDataReader.Benchmarks/SectorChain.cs new file mode 100644 index 00000000..2281b4e6 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/SectorChain.cs @@ -0,0 +1,205 @@ +using System.Collections; +using System.Reflection; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class SectorChain +{ + private const uint EndOfChain = 0xfffffffe; + private const uint FreeSpace = 0xffffffff; + private List _table = []; + private uint _first; + private Func, List> _current = null!; + + [Params("Small16", "Sparse16", "Medium1024", "Large16384", "Fragmented16384", "10x10000.xls", "BigFormatted.xls", "Issue184_FATSectors.xls")] + public string Scenario { get; set; } = string.Empty; + + [GlobalSetup] + public void Setup() + { + var type = typeof(ExcelReaderFactory).Assembly.GetType("ExcelDataReader.Core.CompoundFormat.CompoundDocument")!; + _current = (Func, List>)type.GetMethod("GetSectorChain", BindingFlags.Static | BindingFlags.NonPublic)! + .CreateDelegate(typeof(Func, List>)); + + if (Scenario.EndsWith(".xls", StringComparison.Ordinal)) + { + using var stream = typeof(SectorChain).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks." + Scenario) + ?? throw new InvalidOperationException("Missing workbook " + Scenario); + object document = Activator.CreateInstance(type, stream)!; + _table = (List)type.GetProperty("SectorTable", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(document)!; + var entries = (IEnumerable)type.GetProperty("Entries", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(document)!; + bool found = false; + foreach (object entry in entries) + { + var entryType = entry.GetType(); + string name = (string)entryType.GetProperty("EntryName")!.GetValue(entry)!; + if (name is not ("Workbook" or "Book")) + continue; + if ((bool)entryType.GetProperty("IsEntryMiniStream")!.GetValue(entry)!) + throw new InvalidOperationException("Workbook uses the mini sector table."); + _first = (uint)entryType.GetProperty("StreamFirstSector")!.GetValue(entry)!; + found = true; + break; + } + + if (!found) + throw new InvalidOperationException("Workbook stream not found."); + } + else + { + int count = Scenario is "Small16" or "Sparse16" ? 16 : Scenario == "Medium1024" ? 1024 : 16384; + _table = Enumerable.Repeat(EndOfChain, Scenario == "Sparse16" ? 30030 : count).ToList(); + uint sector = 0; + _first = sector; + for (int i = 1; i < count; i++) + { + uint next = Scenario == "Fragmented16384" ? (uint)((i * 7411) % count) : (uint)i; + _table[(int)sector] = next; + sector = next; + } + } + + var expected = Original(); + if (!expected.SequenceEqual(Current()) || !expected.SequenceEqual(Hybrid()) || + !expected.SequenceEqual(HashSet()) || !expected.SequenceEqual(BitSet())) + throw new InvalidOperationException("Sector chain implementations disagree."); + Console.WriteLine($"Scenario {Scenario}: {expected.Count} sectors, {_table.Count} FAT entries."); + + var savedTable = _table; + uint savedFirst = _first; + foreach (int length in new[] { 1, 64 }) + { + _table = Enumerable.Range(1, length).Select(i => (uint)i).ToList(); + _table[length - 1] = length == 1 ? 0u : 7u; + _first = 0; + CheckCycle(Original); + CheckCycle(Current); + CheckCycle(Hybrid); + CheckCycle(HashSet); + CheckCycle(BitSet); + } + + _table = savedTable; + _first = savedFirst; + } + + [Benchmark(Baseline = true)] + public List Original() + { + List chain = []; + uint sector = _first; + while (sector != EndOfChain) + { + chain.Add(sector); + sector = Next(sector); + if (chain.Contains(sector)) + throw new InvalidOperationException("Cyclic sector chain"); + } + + Trim(chain); + return chain; + } + + [Benchmark] + public List Current() => _current(_first, _table); + + [Benchmark] + public List Hybrid() + { + const int threshold = 32; + List chain = []; + HashSet visited = null; + uint sector = _first; + while (sector != EndOfChain) + { + if (visited == null && chain.Count < threshold) + { + if (chain.Contains(sector)) + throw new InvalidOperationException("Cyclic sector chain"); + } + else + { + visited ??= new HashSet(chain); + if (!visited.Add(sector)) + throw new InvalidOperationException("Cyclic sector chain"); + } + + chain.Add(sector); + sector = Next(sector); + } + + Trim(chain); + return chain; + } + + [Benchmark] + public List HashSet() + { + List chain = []; + var visited = new HashSet(); + uint sector = _first; + while (sector != EndOfChain) + { + if (!visited.Add(sector)) + throw new InvalidOperationException("Cyclic sector chain"); + chain.Add(sector); + sector = Next(sector); + } + + Trim(chain); + return chain; + } + + [Benchmark] + public List BitSet() + { + List chain = []; + var visited = new uint[(int)((_table.Count + 31L) / 32)]; + uint sector = _first; + while (sector != EndOfChain) + { + if (sector < _table.Count) + { + int index = (int)(sector >> 5); + uint bit = 1u << (int)(sector & 31); + if ((visited[index] & bit) != 0) + throw new InvalidOperationException("Cyclic sector chain"); + visited[index] |= bit; + } + + chain.Add(sector); + sector = Next(sector); + } + + Trim(chain); + return chain; + } + + private static void CheckCycle(Func> traverse) + { + try + { + traverse(); + } + catch (InvalidOperationException) + { + return; + } + catch (Exception ex) when (ex.GetType().FullName == "ExcelDataReader.Exceptions.CompoundDocumentException") + { + return; + } + + throw new InvalidOperationException("Sector chain cycle was not detected."); + } + + private static void Trim(List chain) + { + while (chain.Count > 0 && chain[chain.Count - 1] == FreeSpace) + chain.RemoveAt(chain.Count - 1); + } + + private uint Next(uint sector) => sector < _table.Count ? _table[(int)sector] : EndOfChain; +} diff --git a/src/ExcelDataReader.Benchmarks/SharedStringConstruction.cs b/src/ExcelDataReader.Benchmarks/SharedStringConstruction.cs new file mode 100644 index 00000000..e2379074 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/SharedStringConstruction.cs @@ -0,0 +1,42 @@ +using System.Reflection; +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class SharedStringConstruction +{ + private string _path; + private object _configuration; + private MethodInfo _create; + + [Params("Default", "SpillToDisk1", "SpillToDisk256")] + public string Storage { get; set; } + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + _path = Environment.GetEnvironmentVariable("EDR_SST_INPUT") + ?? throw new InvalidOperationException("Set EDR_SST_INPUT to an existing benchmark workbook."); + string library = Environment.GetEnvironmentVariable("EDR_SST_LIBRARY"); + Assembly assembly = string.IsNullOrEmpty(library) ? typeof(ExcelReaderFactory).Assembly : Assembly.LoadFile(Path.GetFullPath(library)); + Type configurationType = assembly.GetType("ExcelDataReader.ExcelReaderConfiguration")!; + _configuration = Activator.CreateInstance(configurationType)!; + configurationType.GetProperty("SinglePassMode")!.SetValue(_configuration, true); + configurationType.GetProperty("SharedStringStorageMode")!.SetValue( + _configuration, + Enum.Parse(assembly.GetType("ExcelDataReader.SharedStringStorageMode")!, Storage == "Default" ? "Default" : "SpillToDisk")); + configurationType.GetProperty("SharedStringSpillThreshold")!.SetValue(_configuration, (Storage == "SpillToDisk1" ? 1L : 256L) * 1024 * 1024); + configurationType.GetProperty("SharedStringTemporaryDirectory")!.SetValue(_configuration, Environment.CurrentDirectory); + _create = assembly.GetType("ExcelDataReader.ExcelReaderFactory")!.GetMethod("CreateReader", [typeof(Stream), configurationType])!; + } + + [Benchmark] + public void Open() + { + using var input = File.OpenRead(_path); + using var reader = (IDisposable)_create.Invoke(null, [input, _configuration])!; + } +} diff --git a/src/ExcelDataReader.Benchmarks/SharedStringIo.cs b/src/ExcelDataReader.Benchmarks/SharedStringIo.cs new file mode 100644 index 00000000..93a50b24 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/SharedStringIo.cs @@ -0,0 +1,174 @@ +using System.Diagnostics; +using System.Reflection; +using System.Text; +#if NET8_0_OR_GREATER +using System.Text.Json; +#endif +using ExcelDataReader.TestFixtures; + +namespace ExcelDataReader.Benchmarks; + +internal static class SharedStringIo +{ + public static void Run() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + string library = Environment.GetEnvironmentVariable("EDR_SST_LIBRARY"); + Assembly assembly = string.IsNullOrEmpty(library) ? typeof(ExcelReaderFactory).Assembly : Assembly.LoadFile(Path.GetFullPath(library)); + foreach (string backend in new[] { "Memory", "File" }) + { + foreach (string pattern in new[] { "Sequential", "Permuted", "Random", "Hot" }) + { + for (int iteration = -3; iteration < 5; iteration++) + Measure(assembly, backend, pattern, iteration); + } + } + } + + private static void Measure(Assembly assembly, string backend, string pattern, int iteration) + { + const int count = 100000; + const int length = 64; + string[] values = Enumerable.Range(0, count).Select(i => SharedStringWorkbook.Value(i, length, pattern == "Hot")).ToArray(); + Type configurationType = assembly.GetType("ExcelDataReader.ExcelReaderConfiguration")!; + object configuration = Activator.CreateInstance(configurationType)!; + configurationType.GetProperty("SharedStringStorageMode")!.SetValue(configuration, Enum.Parse(assembly.GetType("ExcelDataReader.SharedStringStorageMode")!, "SpillToDisk")); + configurationType.GetProperty("SharedStringSpillThreshold")!.SetValue(configuration, 1024L * 1024); + configurationType.GetProperty("SharedStringTemporaryDirectory")!.SetValue(configuration, Environment.CurrentDirectory); + var streams = new Dictionary(); + Func factory = (directory, kind) => + { + Stream stream = backend == "Memory" + ? new MemoryStream() + : new FileStream(Path.Combine(directory, "ExcelDataReader-io-" + Guid.NewGuid().ToString("N") + "-" + kind), FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.DeleteOnClose); + var counted = new CountingStream(stream); + streams.Add(kind, counted); + return counted; + }; + Type storeType = assembly.GetType("ExcelDataReader.Core.AutoSharedStringStore")!; + object store = storeType.GetConstructors()[0].Invoke([configuration, factory]); + using var disposable = (IDisposable)store; + var add = (Action)storeType.GetMethod("Add")!.CreateDelegate(typeof(Action), store); + var seal = (Action)storeType.GetMethod("Seal")!.CreateDelegate(typeof(Action), store); + var get = (Func)storeType.GetMethod("GetString")!.CreateDelegate(typeof(Func), store); + Func decoded = index => values[index]; + var timer = Stopwatch.StartNew(); + ulong expected = ReadValues(decoded, values, pattern); + double decodedLookupMs = timer.Elapsed.TotalMilliseconds; + timer.Restart(); + foreach (string value in values) + add(value); + seal(); + double constructionMs = timer.Elapsed.TotalMilliseconds; + var constructionIo = streams.ToDictionary(pair => pair.Key, pair => pair.Value.Snapshot()); + foreach (CountingStream stream in streams.Values) + stream.Reset(); + timer.Restart(); + int references = SharedStringWorkbook.References(count, pattern); + ulong hash = ReadValues(get, values, pattern); + double lookupMs = timer.Elapsed.TotalMilliseconds; + if (hash != expected) + throw new InvalidOperationException("Direct store checksum mismatch."); + var lookupIo = streams.ToDictionary(pair => pair.Key, pair => pair.Value.Snapshot()); + long residentBytes = (long)storeType.GetProperty("ResidentBytes", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(store)!; + if (iteration < 0) + return; + var result = new { backend, pattern, iteration, count, length, references, constructionMs, decodedLookupMs, lookupMs, hash, residentBytes, constructionIo, lookupIo }; +#if NET8_0_OR_GREATER + Console.WriteLine(JsonSerializer.Serialize(result)); +#else + Console.WriteLine(string.Join("; ", result.GetType().GetProperties().Select(p => p.Name + "=" + p.GetValue(result)))); + foreach (string kind in streams.Keys) + Console.WriteLine(kind + ": construction " + constructionIo[kind] + "; lookup " + lookupIo[kind]); +#endif + } + + private static ulong ReadValues(Func get, string[] values, string pattern) + { + ulong hash = 14695981039346656037; + int references = SharedStringWorkbook.References(values.Length, pattern); + for (int position = 0; position < references; position++) + { + int index = SharedStringWorkbook.Reference(position, values.Length, pattern); + string actual = get(index); + if (actual != values[index]) + throw new InvalidOperationException("Direct store changed string contents."); + hash = SharedStringWorkbook.Hash(hash, actual); + } + + return hash; + } + + private sealed class CountingStream(Stream inner) : Stream + { + private long _reads; + private long _readBytes; + private long _writes; + private long _writeBytes; + private long _seeks; + private int _largestRead; + + public override bool CanRead => inner.CanRead; + + public override bool CanSeek => inner.CanSeek; + + public override bool CanWrite => inner.CanWrite; + + public override long Length => inner.Length; + + public override long Position + { + get + { + return inner.Position; + } + + set + { + _seeks++; + inner.Position = value; + } + } + + public object Snapshot() => new { Reads = _reads, ReadBytes = _readBytes, Writes = _writes, WriteBytes = _writeBytes, Seeks = _seeks, LargestRead = _largestRead }; + + public void Reset() + { + _reads = _readBytes = _writes = _writeBytes = _seeks = 0; + _largestRead = 0; + } + + public override void Flush() => inner.Flush(); + + public override int Read(byte[] buffer, int offset, int count) + { + _reads++; + _largestRead = Math.Max(_largestRead, count); + int read = inner.Read(buffer, offset, count); + _readBytes += read; + return read; + } + + public override long Seek(long offset, SeekOrigin origin) + { + _seeks++; + return inner.Seek(offset, origin); + } + + public override void SetLength(long value) => inner.SetLength(value); + + public override void Write(byte[] buffer, int offset, int count) + { + _writes++; + _writeBytes += count; + inner.Write(buffer, offset, count); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + inner.Dispose(); + base.Dispose(disposing); + } + } +} diff --git a/src/ExcelDataReader.Benchmarks/SharedStringStorage.cs b/src/ExcelDataReader.Benchmarks/SharedStringStorage.cs new file mode 100644 index 00000000..1a1514ee --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/SharedStringStorage.cs @@ -0,0 +1,241 @@ +#nullable enable + +using System.Diagnostics; +using System.Globalization; +using System.IO.Compression; +using System.Reflection; +using System.Text; +#if NET8_0_OR_GREATER +using System.Text.Json; +#endif +using BenchmarkDotNet.Attributes; +using ExcelDataReader.TestFixtures; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class SharedStringStorage +{ + private string _path = string.Empty; + + [Params("xlsx", "xlsb", "xls")] + public string Format { get; set; } = "xlsx"; + + [Params("Sequential", "Permuted")] + public string Pattern { get; set; } = "Sequential"; + + [Params(1000000)] + public int Count { get; set; } + + [Params(64)] + public int Length { get; set; } + + [Params("Default", "SpillToDisk1", "SpillToDisk16", "SpillToDisk64", "SpillToDisk256")] + public string Storage { get; set; } = "Default"; + + private (long Cells, long Characters, ulong Checksum) ExpectedResult { get; set; } + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + _path = Path.Combine(Environment.CurrentDirectory, "ExcelDataReader-sst-" + Guid.NewGuid().ToString("N") + "." + Format); + SharedStringWorkbook.Create(_path, Format, Count, Length, Pattern); + var actual = Read(_path, Configuration("Default", false)); + ExpectedResult = Expected(Count, Length, Pattern); + if (actual != ExpectedResult) + throw new InvalidOperationException("Generated corpus failed output validation."); + } + + [GlobalCleanup] + public void Cleanup() => File.Delete(_path); + + [Benchmark] + public long ReadAll() + { + var actual = Read(_path, Configuration(Storage, false)); + if (actual != ExpectedResult) + throw new InvalidOperationException("Storage mode changed workbook output."); + return actual.Cells; + } + + internal static (long Cells, long Characters, ulong Checksum) Read(string path, ExcelReaderConfiguration configuration) + { + using var stream = File.OpenRead(path); + using var reader = ExcelReaderFactory.CreateReader(stream, configuration); + long cells = 0; + long characters = 0; + ulong checksum = 14695981039346656037; + do + { + while (reader.Read()) + { + for (int c = 0; c < reader.FieldCount; c++) + { + if (reader.GetValue(c) is string value) + { + cells++; + characters += value.Length; + checksum = SharedStringWorkbook.Hash(checksum, value); + } + } + } + } + while (reader.NextResult()); + return (cells, characters, checksum); + } + + internal static void RunScenario(string[] args) + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + if (args[0] == "--sst-generate") + { + string path = args[1]; + int count = int.Parse(args[2], CultureInfo.InvariantCulture); + int length = int.Parse(args[3], CultureInfo.InvariantCulture); + string pattern = args.Length > 4 ? args[4] : "Sequential"; + bool unicode = args.Length > 5 && bool.Parse(args[5]); + SharedStringWorkbook.Create(path, Path.GetExtension(path).TrimStart('.'), count, length, pattern, unicode); + var actual = Read(path, new ExcelReaderConfiguration()); + if (actual != Expected(count, length, pattern, unicode)) + throw new InvalidOperationException("Generated corpus failed output validation."); + Print(new { Path = path, Seed = 741, Count = count, Length = length, Pattern = pattern, Unicode = unicode, Bytes = new FileInfo(path).Length, SstBytes = SstBytes(path), actual.Cells, actual.Characters, actual.Checksum }); + return; + } + + string input = args[1]; + bool singlePass = args.Length > 2 && bool.Parse(args[2]); + string storage = args.Length > 3 ? args[3] : "Default"; + var configuration = Configuration(storage, singlePass); + using var process = Process.GetCurrentProcess(); + WarmUp(); + long baseline = GC.GetTotalMemory(true); + long baselineWorkingSet = process.WorkingSet64; + var timer = Stopwatch.StartNew(); + using var stream = File.OpenRead(input); + using var reader = ExcelReaderFactory.CreateReader(stream, configuration); + double constructionMs = timer.Elapsed.TotalMilliseconds; + long retainedAfterOpen = GC.GetTotalMemory(true) - baseline; + object? store = GetStore(reader); + bool spilledAfterOpen = GetStatistic(store, "HasSpilled"); + long accountedBytes = GetStatistic(store, "ResidentBytes"); + long diskBytes = GetStatistic(store, "DiskBytes"); + long sampledHeapPeak = GC.GetTotalMemory(false); + long? retainedAfterPartialRead = null; + long cells = 0; + long characters = 0; + ulong checksum = 14695981039346656037; + timer.Restart(); + do + { + while (reader.Read()) + { + for (int c = 0; c < reader.FieldCount; c++) + { + if (reader.GetValue(c) is string value) + { + cells++; + characters += value.Length; + checksum = SharedStringWorkbook.Hash(checksum, value); + } + } + + if (cells % 4096 < 4) + sampledHeapPeak = Math.Max(sampledHeapPeak, GC.GetTotalMemory(false)); + if (retainedAfterPartialRead == null && cells >= 10000) + retainedAfterPartialRead = GC.GetTotalMemory(true) - baseline; + } + } + while (reader.NextResult()); + double traversalMs = timer.Elapsed.TotalMilliseconds; + long retainedAfterRead = GC.GetTotalMemory(true) - baseline; + accountedBytes = Math.Max(accountedBytes, GetStatistic(store, "ResidentBytes")); + bool spilled = GetStatistic(store, "HasSpilled"); + diskBytes = GetStatistic(store, "DiskBytes"); + process.Refresh(); + long peakWorkingSet = process.PeakWorkingSet64; + reader.Dispose(); + store = null; + long retainedAfterDispose = GC.GetTotalMemory(true) - baseline; + Print(new { Path = input, Storage = storage, configuration.SinglePassMode, ServerGC = System.Runtime.GCSettings.IsServerGC, constructionMs, traversalMs, cells, characters, checksum, retainedAfterOpen, retainedAfterPartialRead, retainedAfterRead, retainedAfterDispose, baselineWorkingSet, peakWorkingSet, sampledHeapPeak, spilledAfterOpen, spilled, accountedBytes, diskBytes }); + } + + private static (long Cells, long Characters, ulong Checksum) Expected(int count, int length, string pattern, bool unicode = false) + { + int references = SharedStringWorkbook.References(count, pattern); + ulong hash = 14695981039346656037; + for (int i = 0; i < references; i++) + hash = SharedStringWorkbook.Hash(hash, SharedStringWorkbook.Value(SharedStringWorkbook.Reference(i, count, pattern), length, unicode)); + return (references, (long)references * length, hash); + } + + private static ExcelReaderConfiguration Configuration(string storage, bool singlePass) => new() + { + SinglePassMode = singlePass, + SharedStringStorageMode = storage switch + { + "Default" => SharedStringStorageMode.Default, + "SpillToDisk1" or "SpillToDisk16" or "SpillToDisk64" or "SpillToDisk256" => SharedStringStorageMode.SpillToDisk, + _ => throw new ArgumentException("Unknown storage profile.", nameof(storage)), + }, + SharedStringSpillThreshold = storage switch + { + "SpillToDisk1" => 1024L * 1024, + "SpillToDisk16" => 16L * 1024 * 1024, + "SpillToDisk256" => 256L * 1024 * 1024, + _ => 64L * 1024 * 1024, + }, + SharedStringTemporaryDirectory = Environment.CurrentDirectory, + }; + + private static object? GetStore(IExcelDataReader reader) + { + object? workbook = reader.GetType().GetProperty("Workbook", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(reader); + return workbook?.GetType().GetField("_stringStore", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(workbook); + } + + private static long SstBytes(string path) + { + using var input = File.OpenRead(path); + if (Path.GetExtension(path) != ".xls") + { + using var archive = new ZipArchive(input, ZipArchiveMode.Read); + return archive.Entries.Single(e => e.FullName.StartsWith("xl/sharedStrings.", StringComparison.Ordinal)).Length; + } + + using var reader = new BinaryReader(input); + long bytes = 0; + while (input.Position < input.Length) + { + ushort id = reader.ReadUInt16(); + ushort size = reader.ReadUInt16(); + if (id == 0xA) + break; + if (id is 0xFC or 0x3C) + bytes += 4L + size; + input.Position += size; + } + + return bytes; + } + + private static T GetStatistic(object? store, string name) => + store == null ? default! : (T)store.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(store)!; + + private static void WarmUp() + { + using var input = new MemoryStream(AllocationTestWorkbook.CreateXlsx(["warmup"], true)); + using var reader = ExcelReaderFactory.CreateReader(input); + reader.Read(); + reader.GetString(0); + } + + private static void Print(object value) + { +#if NET8_0_OR_GREATER + Console.WriteLine(JsonSerializer.Serialize(value)); +#else + Console.WriteLine(string.Join("; ", value.GetType().GetProperties().Select(p => p.Name + "=" + p.GetValue(value)))); +#endif + } +} diff --git a/src/ExcelDataReader.Benchmarks/SharedStringStorage.md b/src/ExcelDataReader.Benchmarks/SharedStringStorage.md new file mode 100644 index 00000000..22dbc946 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/SharedStringStorage.md @@ -0,0 +1,347 @@ +# Shared string storage: details and benchmarks + +See the [reader configuration example](../../README.md#large-shared-string-tables). + +## Storage behavior + +XLSX, XLSB, and BIFF8 XLS use shared string tables (SSTs). `Default` eagerly +stores decoded strings in the normal in-memory list. Opt-in `SpillToDisk` uses +the same representation until the threshold is exceeded. Before spill, +SpillToDisk lookups reuse stored values without an additional decoded cache. +Declared XML SST capacity is reserved only when it fits within the remaining +budget. + +Both binary formats synchronously send completed strings through the same +borrowed UTF-16 sink. The in-memory table decodes and owns each string during +the call; the spill store consumes the buffer without retaining it and writes +valid UTF-16 code units to disk after spill. XLS uses its own +continuation-aware parser and reuses one assembly buffer; XLSB reads standalone +string records directly from each record buffer. Their parsing state machines +remain separate. Eager Default XLS decodes the complete SST during workbook +opening, so short-circuit reads still pay that decoding cost. XLSB trailing +rich-text and phonetic data are ignored. A character count that does not fit +within an XLSB record raises the standard BIFF string-size error. + +### Eager XLS policy comparison (2026-10-07) + +The selected implementation was compared with the previous lazy XLS path using +100,000 unique 128-character strings. Times are full open/read/dispose totals; +allocations cover opening plus traversal. + +| Runtime / workload | Lazy ms | Eager ms | Time change | Allocation lazy → eager | +| --- | ---: | ---: | ---: | ---: | +| .NET 10 sequential full | 106.0 | 90.7 | -14.5% | 81.94 → 50.57 MiB | +| .NET 10 hot full | 138.2 | 105.8 | -23.5% | 88.04 → 56.67 MiB | +| .NET 10 random full | 111.5 | 90.7 | -18.6% | 81.94 → 50.57 MiB | +| .NET 10 sequential 1% | 44.0 | 60.0 | +36.4% | 49.46 → 44.53 MiB | +| .NET Framework sequential full | 440.2 | 402.4 | -8.6% | 82.84 → 51.37 MiB | +| .NET Framework hot full | 614.2 | 586.0 | -4.6% | 88.96 → 57.49 MiB | +| .NET Framework random full | 389.0 | 337.0 | -13.4% | 82.84 → 51.37 MiB | +| .NET Framework sequential 1% | 55.9 | 103.3 | +84.8% | 49.50 → 45.31 MiB | + +The full-read improvement and partial-read regression were explicit policy +tradeoffs, not a workload-independent performance claim. Measurements used +paired, reversed-order processes, checksum/count/identity validation, and +workstation GC on Windows; they are synthetic and do not establish a real-world +workload mix. + +Capacity growth, strings and lookup cache are accounted. When an add exceeds +the budget, SpillToDisk migrates one entry at a time to disk, then releases the +normal table. It does not create a second full decoded table during migration. +The workbook owns and seals the shared store after parsing; reset and sheet +changes retain it. XML whitespace, rich text, escapes, and binary surrogate +replacement retain Default behavior. + +### Disk representation and cache + +After spill, text is stored uniformly as exact UTF-16 little-endian code units. +The disk index uses **16 bytes per entry**, containing a 64-bit byte offset and +32-bit character count with four padding bytes. No resident per-entry disk index +is retained. After flushing all writes, the store creates unnamed, read-only +file mappings. A lazily created view per file is bounded to 64 MiB on 64-bit +processes or 8 MiB on 32-bit processes; the entire file need not fit in a +contiguous address range. Safe bulk reads copy exact code units into the +existing buffers without acquiring or retaining unmanaged pointers. + +Lookup reuses the 32,768-byte serialization buffer as a payload read window +and uses a 4,096-byte index window. Adjacent uncached references in either +direction use buffered aligned read-ahead. Unrelated misses use mapped reads +when covered by the current view, otherwise exact-sized buffered reads. +They do not continually remap large files. This is an explicit access policy, +not a fallback after a mapping error. Strings can cross buffer and view +boundaries, and offsets remain 64-bit. + +Mappings and windows are initialized only after sealing. File lengths are +checked before mapping; index offsets, alignment +and lengths are checked before decoding. Short buffered reads are completed +explicitly; failed fills never expose an unread tail. The additional index +capacity is 4,080 bytes, and mapping/view bookkeeping reserves a conservative +2,048 accounted bytes per nonempty mapped file. The last-value/second-touch +decoded cache is independently bounded. + +The cache budget is min(one eighth of the configured limit, 8 MiB), including +metadata, with at most 4,096 slots. One-off scans do not admit entries. +Oversized values are returned without retention. Reference identity is not +guaranteed after spill. + +### Budget semantics + +`SharedStringSpillThreshold` is measured in bytes, defaults to 64 MiB, and must be +at least 1 MiB in SpillToDisk mode. Default ignores the threshold and temporary directory. + +The SpillToDisk budget accounts for allocated reference capacity (including +unused slots), conservative object/array/string overhead, and retained decoded +strings. Empty strings share the runtime singleton. Disk buffers and cache are +allocated only after spill. + +This is **not a total managed-heap or process-memory limit**. Parser temporaries, +a single decoded string, current rows, input buffering, decryption, workbook +metadata, OS file caches, mapped file pages and values retained by callers are +outside it. Mapping reserves virtual address space, not a resident managed +byte array; touched pages can increase the process working set independently +of the configured budget. The two views together reserve at most 128 MiB on +64-bit or 16 MiB on 32-bit processes, excluding OS alignment/page rounding. +Migration can transiently exceed the threshold while serializing an entry. + +`AsDataSet()` retains its own data. `SinglePassMode` skips worksheet preparation, +but not SST parsing. SST options do not affect CSV, SpreadsheetML, or older XLS +formats without SSTs. + +### Temporary files and failures + +Files are created only when spill occurs, in the configured existing directory. +`SharedStringTemporaryDirectory = null` uses the system temporary directory. +The directory needs read/write permissions and sufficient free space. + +Payload and index files use exclusive delete-on-close handles and bounded +buffers. `Close()`/`Dispose()` releases views and mappings before their backing +streams, independently of `LeaveOpen`. File and mapping creation, view creation, +write, flush, seek and lookup failures propagate; there is no silent fallback +to unbounded RAM or suppression of mapping errors. Spill requires platform +support for persisted memory-mapped files. Windows .NET 10 and .NET Framework +were tested; API availability on the library targets is not a claim of +validation on every operating system. + +Temporary strings are **plaintext even for password-protected workbooks**. +Secure deletion and cleanup after abrupt process termination are not guaranteed. + +## Benchmark corpus + +Large worksheets do not necessarily have large SSTs: `10x10000.xlsx` has only +20 unique strings and a 558-byte SST. The benchmark project includes a streaming +generator with seed 741, unique index prefixes and varied suffixes. It validates +cell counts, character counts and a stable content checksum. + +| Profile | Unique entries | Characters per entry | Purpose | +|---|---:|---:|---| +| Control | 100,000 | 64 | Below the normal 64 MiB threshold | +| Large SST | 1,000,000 | 64 | Compare in-memory storage and actual spill | +| Long strings | 1,000,000 | 256 | Make retained text dominate | + +The generator supports XLSX, XLSB and raw BIFF8 XLS. Reference patterns are +`Sequential`, `Permuted`, `Random`, `Hot` and `Sparse`; an optional boolean +selects non-Latin-1 text. Generation is outside measured operations, and all +modes read the same logical corpus. Large generated files are not committed. + +## Measurements (2026-10-05) + +Windows 11, Core i5-13400F, SDK 10.0.401 / .NET 10.0.12, x64, local C: storage, +Workstation GC. Paired Stopwatch hosts referenced preserved library binaries: +the buffered baseline at commit `325098c` and the current mapped/buffered policy. +Each operation opened the reader with SinglePassMode, completely traversed it, +validated cell/character counts and a stable checksum, and disposed it. +The generated files were identical for both versions. + +There were three warmups and eight measured iterations per process, two +processes per version/workload, with version order reversed on the second run. +All 16 observations were retained. `DOTNET_TieredCompilation=0` avoided tiering +transitions observed in short processes. These are warmed-cache comparisons, +not cold-storage measurements or BenchmarkDotNet summaries. Means and sample +standard deviations are milliseconds; they should not be mixed with timings +from different JIT settings or harnesses. + +| Format / pattern / entries | Current Default ms | Buffered baseline SpillToDisk1 ms | Current SpillToDisk1 ms | +|---|---:|---:|---:| +| XLSX / Sequential / 100,000 | 199.30 ± 7.66 | 289.69 ± 13.44 | 272.83 ± 22.84 | +| XLSB / Sequential / 100,000 | 74.83 ± 5.47 | 141.09 ± 10.24 | 145.83 ± 14.94 | +| XLS / Sequential / 100,000 | 102.18 ± 8.40 | 125.18 ± 12.94 | 126.29 ± 15.57 | +| XLSB / Permuted / 100,000 | 72.82 ± 4.30 | 139.75 ± 17.91 | 148.03 ± 16.59 | +| XLSB / Random / 100,000 | 80.82 ± 8.35 | 655.21 ± 38.39 | 165.12 ± 18.16 | +| XLSX / Hot Unicode / 100,000 | 256.98 ± 9.15 | 328.08 ± 25.36 | 325.31 ± 26.39 | +| XLSB / Sequential / 1,000,000 | 745.99 ± 17.08 | 1,486.83 ± 241.47 | 1,414.06 ± 287.46 | +| XLSB / Random / 1,000,000 | 890.28 ± 48.09 | 9,136.56 ± 392.74 | 3,725.89 ± 169.35 | + +Random full traversal improved about 4.0x at 100,000 entries and 2.5x at one +million. The million-entry payload exceeds a view; out-of-view random misses +therefore still perform buffered I/O. Adjacent and hot workloads do not show +a consistent full-operation gain; opening/spill costs remain substantial. +Sequential controls retain checksum `9989736530551659307`, and the million +sequential corpus retains `7742303954537846853`. + +For XLSB random, opening averaged 115.19 → 117.13 ms at 100,000 entries and +1,228.21 → 1,270.90 ms at one million. Traversal averaged 538.63 → 45.72 ms +and 7,896.32 → 2,438.21 ms, respectively. Disposal averaged 1.39 → 2.27 ms +and 12.02 → 16.78 ms. These phases demonstrate that the benefit is in lookup, +not removal of parsing, serialization or disposal costs. The XLSB rows above +predate synchronous XLSB string ingestion; see below for its effect. + +### XLSB string ingestion (2026-10-06) + +A paired Stopwatch host referenced preserved library binaries built from commit +`965037b` and from the current source. Fixtures had 100,000 unique 128-character +entries (ASCII or Cyrillic text) referenced `Sequential`, `Hot` or `Random`; +`Partial` read only the first 16 cells. Profiles were Default, SpillToDisk256 +(no spill) and SpillToDisk1 (spill). Each process ran three warmups and ten +measured operations; two timing processes per version used reversed order, and +a third process per version recorded forced-GC retention. Tiered compilation was +disabled with Workstation GC. Every operation validated cell count, checksum, +SST count and, without spill, reference identity. Values are medians. + +| Profile | Runtime | Opening allocation MiB | Total time change | +|---|---|---:|---:| +| Default, SpillToDisk256 | .NET 10 | 31.04 → 28.75 | -9% to +5% | +| Default, SpillToDisk256 | .NET Framework | 32.28–34.16 → 29.99–31.86 | -13% to +3% | +| SpillToDisk1 | .NET 10 | 29.14 → 1.10 | -11% to -33% | +| SpillToDisk1 | .NET Framework | 30.39–32.26 → 1.52–3.38 | -10% to -41% | + +Without spill, opening allocation falls by 2.29 MiB, the per-string record +objects; retained memory and traversal allocation are unchanged. Most timing +differences without spill are within process-to-process variance. A 40-sample +recheck of the largest .NET 10 increase (Hot, SpillToDisk256) measured +136.4 → 129.3 ms. On .NET Framework, lower opening allocation moves a gen2 +collection from opening into traversal, so traversal can be 2–4 ms slower while +total time is still lower. + +With spill, opening no longer allocates a decoded string per entry. For +Cyrillic text, opening medians fell from 78–81 to 52–68 ms on .NET 10, and +from 98–115 to 53–66 ms on .NET Framework. Traversal time and allocation, +accounted resident bytes (83,136, or 156,864 with hot-value caching) and disk +bytes (27,200,000) are unchanged. + +For 1,000,000 unique 64-character ASCII entries read sequentially on .NET 10, +Default opening allocation fell from 183.90 to 161.01 MiB and total time from +731 to 669 ms. SpillToDisk1 opening allocation fell from 168.06 to 1.11 MiB and +total time from 976 to 868 ms, with unchanged 83,008 accounted and 144,000,000 +disk bytes. + +### XLS spill ingestion (2026-10-06) + +This comparison predates the common eager Default policy documented above. +Default-specific figures below describe the source used for this 2026-10-06 +comparison, not the selected eager implementation. + +The XLS parser sends each assembled UTF-16 string synchronously to the same +`ISharedStringSink` used by XLSB, for both Default and SpillToDisk. It reuses +one assembly buffer and does not create an `XlsUnicodeString` wrapper per +entry. The XLS continuation/parser state machine remains format-specific. + +A Stopwatch host referenced preserved `net8.0` and `net462` library binaries +from commit `ca4e31c` and the candidate. Each corpus had 100,000 unique +128-character strings, either compressed single-byte text or Unicode, with +sequential references. Two processes per binary/workload ran three warmups and +ten measured full open/read/dispose operations; baseline/candidate process +order was reversed. Tiered compilation was disabled on .NET 10. Times below +are medians across 20 operations in ms; allocation is the average opening +allocation in MiB. + +| Runtime | Mode / text | Opening allocation baseline → candidate | Open ms baseline → candidate | Full ms baseline → candidate | +|---|---|---:|---:|---:| +| .NET 10 | SpillToDisk256 / narrow | 75.06 → 44.47 | 59.57 → 69.34 | 80.68 → 90.40 | +| .NET 10 | SpillToDisk256 / Unicode | 87.82 → 57.13 | 67.69 → 65.55 | 90.98 → 91.06 | +| .NET 10 | SpillToDisk1 / narrow | 47.41 → 16.81 | 61.93 → 63.95 | 104.20 → 106.17 | +| .NET 10 | SpillToDisk1 / Unicode | 60.17 → 29.47 | 62.30 → 62.97 | 103.54 → 104.59 | +| .NET Framework | SpillToDisk256 / narrow | 75.95 → 45.26 | 110.12 → 101.66 | 337.41 → 326.56 | +| .NET Framework | SpillToDisk256 / Unicode | 88.40 → 57.59 | 127.24 → 107.48 | 350.02 → 330.12 | +| .NET Framework | SpillToDisk1 / narrow | 47.49 → 16.80 | 75.84 → 73.67 | 333.90 → 333.10 | +| .NET Framework | SpillToDisk1 / Unicode | 59.90 → 29.14 | 79.86 → 74.44 | 339.25 → 336.10 | + +The parser handoff lowers opening allocation by about 30.6 MiB in all four +text/runtime combinations; for forced spill that is 65% for narrow and 51% for +Unicode input on .NET 10. Forced-spill full-operation times stayed within about 2% of baseline medians. +The no-spill SpillToDisk256 narrow-text profile was about 12% slower on .NET 10, +while the Unicode control was unchanged and both .NET Framework controls were +faster. This is an allocation benefit, not a consistent throughput improvement. Default +retained identical opening allocation (49.13/61.88 MiB on .NET 10 and +49.17/61.59 MiB on .NET Framework) and matching checksums. All modes returned +100,000 strings with the expected checksum; the forced-spill payload and index +totaled 27,200,000 bytes. + +A real-file direct-store diagnostic, independently of workbook parsing, used +the same warmup/repetition scheme and JIT setting. At 100,000 entries: + +| Lookup pattern | Buffered baseline ms | Current ms | +|---|---:|---:| +| Sequential | 17.37 ± 0.73 | 17.72 ± 1.97 | +| Permuted | 17.03 ± 1.23 | 16.77 ± 0.75 | +| Random | 514.77 ± 16.68 | 39.59 ± 1.29 | + +Sealing/flushing plus mapping setup averaged 0.15 ms for the random mapped +case versus 0.02 ms buffered. Mapping setup allocated 496 managed bytes; +first lookup, including lazy view creation, averaged 0.038 versus 0.026 ms. +Lookup allocation itself was unchanged at 15,199,848 bytes in that diagnostic. +Full random traversals allocated 38.5967 → 38.5978 MiB at 100,000 entries +and 383.6361 → 383.6372 MiB at one million. + +### Managed memory versus mapped pages + +Fresh `--sst-memory` forced-GC checkpoints are **not timing evidence**. +For the million-entry sequential XLSB corpus, SpillToDisk1 had 144,000,000 disk +bytes, 83,008 accounted bytes after traversal, 64,192 retained managed bytes +after opening and 97,384 after traversal. Mapping bookkeeping +adds 4,096 accounted bytes relative to the buffered baseline. + +Separate fresh-process random checkpoints recorded active view capacity, +managed retention and aggregate process working set. At 100,000 entries the +two active views covered 14,400,000 bytes, and working set changed from +69.14 MB after traversal to 54.78 MB after disposal. At one million entries, +view capacity was 83,108,864 bytes (64 MiB payload plus 16 MB index), and +working set changed from 137.86 to 54.76 MB. Views were absent after disposal. +Managed retention stayed roughly 0.2 MB after traversal in these cold-host +checkpoints, including runtime/parser metadata and diagnostic overhead. + +View capacity is virtual coverage, not a measurement of resident pages. +Working set is process-wide and includes runtime memory, not just mappings; +the observed drops are not a portable formula for mapped RAM. These results +illustrate why the managed SST budget is not a process-memory limit. + +The `--sst-io` diagnostic deliberately wraps injected streams. Such wrappers +exercise the buffered path, not the real-file mapped path. Its counts are +managed stream calls, **not OS I/O operations**, and MemoryStream timings +include validation, hashing, allocation and caching rather than isolating +decoding. Use complete real-file traversal to measure mapped access. + +All four library targets and three benchmark targets built without warnings. +Full tests passed on .NET 10 and .NET Framework; additional store tests passed +with the Framework host explicitly forced to x86. A sparse-file diagnostic +verified a 32 KiB read crossing a 64 KiB view boundary beyond a 4 GiB offset +on x64 without allocating a multi-gigabyte managed array. Framework throughput, +non-Windows execution and controlled cold-cache performance were not measured. + +## Reproduction + +Run from the repository root with an existing writable corpus directory. +Explicit generation leaves files for reuse; remove them when finished. + +```powershell +dotnet run --project src\ExcelDataReader.Benchmarks\ExcelDataReader.Benchmarks.csproj -c Release -f net10.0 -- --sst-generate C:\bench\control.xlsx 100000 64 Sequential +dotnet run --project src\ExcelDataReader.Benchmarks\ExcelDataReader.Benchmarks.csproj -c Release -f net10.0 --no-build -- --sst-generate C:\bench\million.xlsx 1000000 64 Sequential +dotnet run --project src\ExcelDataReader.Benchmarks\ExcelDataReader.Benchmarks.csproj -c Release -f net10.0 --no-build -- --sst-memory C:\bench\million.xlsx true SpillToDisk64 +$env:EDR_SST_INPUT = 'C:\bench\control.xlsx' +dotnet run --project src\ExcelDataReader.Benchmarks\ExcelDataReader.Benchmarks.csproj -c Release -f net10.0 --no-build -- --filter "*SharedStringTraversal*" --job Short --launchCount 1 --warmupCount 3 --iterationCount 5 --artifacts artifacts\sst-auto +dotnet run --project src\ExcelDataReader.Benchmarks\ExcelDataReader.Benchmarks.csproj -c Release -f net10.0 --no-build -- --sst-io +``` + +The extension selects the format. For Unicode/hot data, append `Hot true` instead +of `Sequential` to the generation command. The memory harness boolean selects +SinglePassMode; profiles include Default, SpillToDisk1, SpillToDisk16, SpillToDisk64 and SpillToDisk256. +Thresholds are in MiB. Confirm actual spill: SpillToDisk256 is not universally below +budget. Use `--filter "*SharedStringConstruction*"` for opening-only timings, +or `--filter "*SharedStringStorage*"` for generated million-entry comparisons. + +The net10.0 host selects the library's net10.0 build. Use `-f net462` on Windows +for the Framework host. Optional `EDR_SST_LIBRARY` selects a compatible preserved +library for construction-only baseline comparisons; unset it for the project +reference. It also selects the library for the direct-store `--sst-io` diagnostic, +which runs independently of `EDR_SST_INPUT` and creates delete-on-close files in +the current directory. Run builds, tests and benchmarks serially because output directories +are shared. Forced-GC harness timings are diagnostic, not throughput evidence. diff --git a/src/ExcelDataReader.Benchmarks/SharedStringTraversal.cs b/src/ExcelDataReader.Benchmarks/SharedStringTraversal.cs new file mode 100644 index 00000000..ee2b1beb --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/SharedStringTraversal.cs @@ -0,0 +1,40 @@ +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class SharedStringTraversal +{ + private string _path; + private (long Cells, long Characters, ulong Checksum) _expected; + + [Params("Default", "SpillToDisk1", "SpillToDisk256")] + public string Storage { get; set; } + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + _path = Environment.GetEnvironmentVariable("EDR_SST_INPUT") + ?? throw new InvalidOperationException("Set EDR_SST_INPUT to an existing benchmark workbook."); + _expected = SharedStringStorage.Read(_path, Configuration("Default")); + } + + [Benchmark] + public long ReadAll() + { + var actual = SharedStringStorage.Read(_path, Configuration(Storage)); + if (actual != _expected) + throw new InvalidOperationException("Storage mode changed workbook output."); + return actual.Cells; + } + + private static ExcelReaderConfiguration Configuration(string storage) => new() + { + SinglePassMode = true, + SharedStringStorageMode = storage == "Default" ? SharedStringStorageMode.Default : SharedStringStorageMode.SpillToDisk, + SharedStringSpillThreshold = (storage == "SpillToDisk1" ? 1L : 256L) * 1024 * 1024, + SharedStringTemporaryDirectory = Environment.CurrentDirectory, + }; +} diff --git a/src/ExcelDataReader.Benchmarks/SinglePassRead.cs b/src/ExcelDataReader.Benchmarks/SinglePassRead.cs new file mode 100644 index 00000000..1faec1a9 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/SinglePassRead.cs @@ -0,0 +1,78 @@ +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class SinglePassRead +{ + private static readonly ExcelReaderConfiguration MultiPassConfig = new(); + private static readonly ExcelReaderConfiguration SinglePassConfig = new() { SinglePassMode = true }; + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + } + + [Benchmark] + public void ReadMultiPassXlsx() + { + using var reader = ExcelReaderFactory.CreateReader( + typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xlsx"), + MultiPassConfig); + Read(reader); + } + + [Benchmark] + public void ReadSinglePassXlsx() + { + using var reader = ExcelReaderFactory.CreateReader( + typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xlsx"), + SinglePassConfig); + Read(reader); + } + + [Benchmark] + public void ReadMultiPassXlsb() + { + using var reader = ExcelReaderFactory.CreateReader( + typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xlsb"), + MultiPassConfig); + Read(reader); + } + + [Benchmark] + public void ReadSinglePassXlsb() + { + using var reader = ExcelReaderFactory.CreateReader( + typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xlsb"), + SinglePassConfig); + Read(reader); + } + + [Benchmark] + public void ReadMultiPassXls() + { + using var reader = ExcelReaderFactory.CreateReader( + typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xls"), + MultiPassConfig); + Read(reader); + } + + [Benchmark] + public void ReadSinglePassXls() + { + using var reader = ExcelReaderFactory.CreateReader( + typeof(OpenXmlFile).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000.xls"), + SinglePassConfig); + Read(reader); + } + + private static void Read(IExcelDataReader reader) + { + while (reader.Read()) + { + } + } +} diff --git a/src/ExcelDataReader.Benchmarks/SpreadsheetStyles.cs b/src/ExcelDataReader.Benchmarks/SpreadsheetStyles.cs new file mode 100644 index 00000000..3e3c1ff0 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/SpreadsheetStyles.cs @@ -0,0 +1,42 @@ +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class SpreadsheetStyles +{ + private byte[] _data = []; + + [Params(1, 16, 256)] + public int Styles { get; set; } + + [Params(1, 10000)] + public int Rows { get; set; } + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + var xml = new StringBuilder(""); + for (int i = 0; i < Styles; i++) + xml.Append(""); + xml.Append(""); + for (int i = 0; i < Rows; i++) + xml.Append("123.5"); + xml.Append("
"); + _data = Encoding.UTF8.GetBytes(xml.ToString()); + } + + [Benchmark] + public double Read() + { + using var reader = ExcelReaderFactory.CreateReader(new MemoryStream(_data, false)); + double sum = 0; + while (reader.Read()) + sum += reader.GetDouble(0); + if (sum != Rows * 123.5) + throw new InvalidOperationException("SpreadsheetML checksum mismatch."); + return sum; + } +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/SpreadsheetValues.cs b/src/ExcelDataReader.Benchmarks/SpreadsheetValues.cs new file mode 100644 index 00000000..bec23164 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/SpreadsheetValues.cs @@ -0,0 +1,66 @@ +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class SpreadsheetValues +{ + private byte[] _data = []; + private object _expected = null!; + + [Params("Number", "NumberDuration", "Date", "DateDuration", "TextDuration", "Boolean", "Text")] + public string Values { get; set; } = string.Empty; + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + var (type, text, expected) = Values switch + { + "Number" => ("Number", "123.5", (object)123.5D), + "NumberDuration" => ("Number", "2.5", TimeSpan.FromDays(2.5)), + "Date" => ("DateTime", "2026-01-02T03:04:05", new DateTime(2026, 1, 2, 3, 4, 5)), + "DateDuration" => ("DateTime", "1900-03-01T12:00:00", TimeSpan.FromDays(61.5)), + "TextDuration" => ("String", "02:30:00", TimeSpan.FromHours(2.5)), + "Boolean" => ("Boolean", "1", true), + "Text" => ("String", "alpha", "alpha"), + _ => throw new InvalidOperationException("Unknown value kind."), + }; + _expected = expected; + bool duration = Values.EndsWith("Duration", StringComparison.Ordinal); + var xml = new StringBuilder(""); + for (int row = 0; row < 10000; row++) + { + xml.Append(""); + for (int column = 0; column < 10; column++) + xml.Append("").Append(text).Append(""); + xml.Append(""); + } + + xml.Append("
"); + _data = Encoding.UTF8.GetBytes(xml.ToString()); + if (Read() != 100000) + throw new InvalidOperationException("Unexpected cell count."); + } + + [Benchmark] + public int Read() + { + using var reader = ExcelReaderFactory.CreateReader(new MemoryStream(_data, writable: false)); + int count = 0; + while (reader.Read()) + { + for (int column = 0; column < reader.FieldCount; column++) + { + if (!Equals(reader.GetValue(column), _expected)) + throw new InvalidOperationException("Unexpected cell value."); + count++; + } + } + + return count; + } +} \ No newline at end of file diff --git a/src/ExcelDataReader.Benchmarks/WorksheetConsumption.cs b/src/ExcelDataReader.Benchmarks/WorksheetConsumption.cs new file mode 100644 index 00000000..233d8a05 --- /dev/null +++ b/src/ExcelDataReader.Benchmarks/WorksheetConsumption.cs @@ -0,0 +1,85 @@ +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace ExcelDataReader.Benchmarks; + +[MemoryDiagnoser] +public class WorksheetConsumption +{ + private byte[] _data = []; + private ExcelReaderConfiguration _configuration = null!; + + [Params("xls", "xlsx", "xlsb", "xml", "csv")] + public string Format { get; set; } = string.Empty; + + [Params(false, true)] + public bool SinglePass { get; set; } + + [Params(false, true)] + public bool ReadValues { get; set; } + + [GlobalSetup] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + _configuration = new ExcelReaderConfiguration { SinglePassMode = SinglePass }; + if (Format is "xls" or "xlsx" or "xlsb") + { + using var stream = typeof(WorksheetConsumption).Assembly.GetManifestResourceStream("ExcelDataReader.Benchmarks.10x10000." + Format)!; + using var buffer = new MemoryStream(); + stream.CopyTo(buffer); + _data = buffer.ToArray(); + return; + } + + var text = new StringBuilder(); + if (Format == "xml") + text.Append(""); + for (int row = 0; row < 10000; row++) + { + if (Format == "csv") + { + text.Append("alpha,beta,gamma,delta,epsilon,zeta,eta,theta,iota,kappa\n"); + } + else + { + text.Append(""); + for (int column = 0; column < 10; column++) + text.Append("alpha"); + text.Append(""); + } + } + + if (Format == "xml") + text.Append("
"); + _data = Encoding.UTF8.GetBytes(text.ToString()); + } + + [Benchmark] + public long Read() + { + using var stream = new MemoryStream(_data, writable: false); + using var reader = Format == "csv" + ? ExcelReaderFactory.CreateCsvReader(stream, _configuration) + : ExcelReaderFactory.CreateReader(stream, _configuration); + long checksum = 0; + while (reader.Read()) + { + checksum++; + if (!ReadValues) + continue; + for (int column = 0; column < reader.FieldCount; column++) + { + checksum += reader.GetValue(column) switch + { + string value => value.Length, + double value => (long)value, + int value => value, + _ => 0, + }; + } + } + + return checksum; + } +} \ No newline at end of file diff --git a/src/ExcelDataReader.ConsoleSample/ExcelDataReader.ConsoleSample.csproj b/src/ExcelDataReader.ConsoleSample/ExcelDataReader.ConsoleSample.csproj new file mode 100644 index 00000000..92bb2b2c --- /dev/null +++ b/src/ExcelDataReader.ConsoleSample/ExcelDataReader.ConsoleSample.csproj @@ -0,0 +1,21 @@ + + + + readersample + Exe + net10.0 + enable + true + + + + + + + + + + + + + diff --git a/src/ExcelDataReader.ConsoleSample/Program.cs b/src/ExcelDataReader.ConsoleSample/Program.cs new file mode 100644 index 00000000..4138e7a7 --- /dev/null +++ b/src/ExcelDataReader.ConsoleSample/Program.cs @@ -0,0 +1,619 @@ +using System.CommandLine; +using System.Data; +using System.Diagnostics; +using System.Text; +using ExcelDataReader; +using Spectre.Console; + +Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + +var rootCommand = new RootCommand("ExcelDataReader sample console application"); +rootCommand.Subcommands.Add(BuildExcelCommand()); +rootCommand.Subcommands.Add(BuildCsvCommand()); +rootCommand.Subcommands.Add(BuildPropertiesCommand()); +rootCommand.Subcommands.Add(BuildCellMetadataCommand(comments: true)); +rootCommand.Subcommands.Add(BuildCellMetadataCommand(comments: false)); +return rootCommand.Parse(args).Invoke(); + +// ---- excel subcommand ------------------------------------------------------- +static Command BuildExcelCommand() +{ + var fileArg = new Argument("file") { Description = "Path to the Excel file (XLS, XLSX, XLSB, XML Spreadsheet 2003)" }; + var sheetNameOpt = new Option("--sheet-name", ["-n"]) { Description = "Filter by sheet name (repeatable; names may contain commas)", AllowMultipleArgumentsPerToken = false }; + var sheetIndexOpt = new Option("--sheet-index", ["-i"]) { Description = "Filter by 1-based sheet index, comma-separated or repeatable (e.g. 2,5,7)", AllowMultipleArgumentsPerToken = false }; + var noHeaderOpt = new Option("--no-header", ["-H"]) { Description = "Don't treat first row as column names" }; + var fillMergedOpt = new Option("--fill-merged") { Description = "Fill merged cell values across the merged range (implies --dataset)" }; + var singlePassOpt = new Option("--single-pass") { Description = "Enable single pass mode (skips pre-scan for row/column counts)" }; + var outputOpt = new Option("--output", ["-o"]) { Description = "Data output format: table, csv, tsv (default: no data output, stats only)", DefaultValueFactory = _ => OutputFormat.None }; + var passwordOpt = new Option("--password", ["-p"]) { Description = "Password for protected workbooks" }; + var encodingOpt = new Option("--encoding", ["-e"]) { Description = "Fallback encoding for XLS BIFF2-5 (default: windows-1252)", DefaultValueFactory = _ => "windows-1252" }; + var dataSetOpt = new Option("--dataset") { Description = "Use AsDataSet extension (loads all data into a DataSet in memory)" }; + + var cmd = new Command("excel", "Read XLS, XLSX, XLSB, or XML Spreadsheet 2003 files"); + cmd.Arguments.Add(fileArg); + cmd.Options.Add(sheetNameOpt); + cmd.Options.Add(sheetIndexOpt); + cmd.Options.Add(noHeaderOpt); + cmd.Options.Add(fillMergedOpt); + cmd.Options.Add(singlePassOpt); + cmd.Options.Add(outputOpt); + cmd.Options.Add(passwordOpt); + cmd.Options.Add(encodingOpt); + cmd.Options.Add(dataSetOpt); + var configureStorage = AddSharedStringOptions(cmd); + + cmd.SetAction(parseResult => + { + var file = parseResult.GetValue(fileArg)!; + var sheetNames = parseResult.GetValue(sheetNameOpt) ?? []; + var sheetIndexTokens = parseResult.GetValue(sheetIndexOpt) ?? []; + var noHeader = parseResult.GetValue(noHeaderOpt); + var fillMerged = parseResult.GetValue(fillMergedOpt); + var singlePass = parseResult.GetValue(singlePassOpt); + var output = parseResult.GetValue(outputOpt); + var password = parseResult.GetValue(passwordOpt); + var encodingName = parseResult.GetValue(encodingOpt)!; + var useDataSet = parseResult.GetValue(dataSetOpt) || fillMerged; + + var nameSet = new HashSet(sheetNames, StringComparer.Ordinal); + var indexSet = ParseSheetIndices(sheetIndexTokens); + + bool hasFilter = nameSet.Count > 0 || indexSet.Count > 0; + + var memBefore = Process.GetCurrentProcess().WorkingSet64; + var sw = Stopwatch.StartNew(); + + using var stream = file.OpenRead(); + var configuration = new ExcelReaderConfiguration + { + Password = password, + FallbackEncoding = Encoding.GetEncoding(encodingName), + SinglePassMode = singlePass, + }; + configureStorage(parseResult, configuration); + using var reader = ExcelReaderFactory.CreateReader(stream, configuration); + + var openMs = sw.ElapsedMilliseconds; + + if (useDataSet) + { + var ds = reader.AsDataSet(new ExcelDataSetConfiguration + { + UseColumnDataType = false, + FilterSheet = (tableReader, sheetIndex) => + { + if (!hasFilter) + return true; + + // sheetIndex is 0-based; expose as 1-based to the user. + var sheetName = tableReader.Name ?? string.Empty; + return nameSet.Contains(sheetName) || indexSet.Contains(sheetIndex + 1); + }, + ConfigureDataTable = _ => new ExcelDataTableConfiguration + { + UseHeaderRow = !noHeader, + FillMergedCellsValue = fillMerged, + } + }); + + var readMs = sw.ElapsedMilliseconds - openMs; + var memAfter = Process.GetCurrentProcess().WorkingSet64; + + PrintStats(openMs, readMs, ds, memBefore, memAfter); + + if (output != OutputFormat.None) + RenderSheets(ds, output); + } + else + { + var sheets = ReadRaw(reader, noHeader, hasFilter, nameSet, indexSet, output); + + var readMs = sw.ElapsedMilliseconds - openMs; + var memAfter = Process.GetCurrentProcess().WorkingSet64; + + PrintRawStats(openMs, readMs, sheets, memBefore, memAfter); + } + }); + + return cmd; +} + +static HashSet ParseSheetIndices(string[] tokens) +{ + var indices = new HashSet(); + foreach (var part in tokens.SelectMany(token => token.Split(','))) + { + if (!int.TryParse(part.Trim(), out int index) || index < 1) + throw new ArgumentException($"Invalid sheet index: '{part.Trim()}' (must be a positive integer)"); + indices.Add(index); + } + + return indices; +} + +static Action AddSharedStringOptions(Command command) +{ + var mode = new Option("--shared-string-storage") { Description = "Shared string storage: Default or SpillToDisk" }; + var threshold = new Option("--shared-string-threshold") { Description = "Spill threshold in bytes (minimum 1048576)", DefaultValueFactory = _ => 64L * 1024 * 1024 }; + var directory = new Option("--shared-string-directory") { Description = "Temporary spill directory (strings are stored as plaintext, including encrypted files)" }; + command.Options.Add(mode); + command.Options.Add(threshold); + command.Options.Add(directory); + return (result, configuration) => + { + configuration.SharedStringStorageMode = result.GetValue(mode); + configuration.SharedStringSpillThreshold = result.GetValue(threshold); + configuration.SharedStringTemporaryDirectory = result.GetValue(directory); + }; +} + +static Command BuildCellMetadataCommand(bool comments) +{ + string description = comments ? "Show stored legacy cell comments" : "Show explicit stored hyperlinks (not formula-generated links)"; + var command = new Command(comments ? "comments" : "links", description + ". Outputs quoted TSV with 1-based row/column coordinates for readable cells. Metadata is loaded lazily and may require an additional scan."); + var file = new Argument("file") { Description = "Path to the Excel file" }; + var password = new Option("--password", ["-p"]) { Description = "Password for protected workbooks" }; + var encoding = new Option("--encoding", ["-e"]) { Description = "Fallback XLS encoding", DefaultValueFactory = _ => "windows-1252" }; + var names = new Option("--sheet-name", ["-n"]) { Description = "Filter by sheet name (repeatable)", AllowMultipleArgumentsPerToken = false }; + var indices = new Option("--sheet-index", ["-i"]) { Description = "Filter by 1-based sheet index, comma-separated or repeatable", AllowMultipleArgumentsPerToken = false }; + var singlePass = new Option("--single-pass") { Description = "Skip the row/column counting pre-scan" }; + command.Arguments.Add(file); + command.Options.Add(password); + command.Options.Add(encoding); + command.Options.Add(names); + command.Options.Add(indices); + command.Options.Add(singlePass); + var configureStorage = AddSharedStringOptions(command); + command.SetAction(result => + { + var nameSet = new HashSet(result.GetValue(names) ?? [], StringComparer.Ordinal); + var indexSet = ParseSheetIndices(result.GetValue(indices) ?? []); + var configuration = new ExcelReaderConfiguration + { + Password = result.GetValue(password), + FallbackEncoding = Encoding.GetEncoding(result.GetValue(encoding)!), + SinglePassMode = result.GetValue(singlePass), + }; + configureStorage(result, configuration); + using var stream = result.GetValue(file)!.OpenRead(); + using var reader = ExcelReaderFactory.CreateReader(stream, configuration); + WriteSeparatedRow(comments ? ["Sheet", "Row", "Column", "Author", "Text"] : ["Sheet", "Row", "Column", "Address", "Tooltip"], '\t'); + int sheet = 0; + do + { + sheet++; + if (nameSet.Count + indexSet.Count > 0 && !nameSet.Contains(reader.Name ?? string.Empty) && !indexSet.Contains(sheet)) + continue; + int row = 0; + while (reader.Read()) + { + row++; + for (int column = 0; column < reader.FieldCount; column++) + { + if (comments) + { + if (reader.GetComment(column) is { } comment) + { + foreach (var message in comment.Messages) + WriteSeparatedRow([reader.Name ?? string.Empty, row.ToString(), (column + 1).ToString(), message.Author ?? string.Empty, message.Text], '\t'); + } + } + else if (reader.GetHyperlink(column) is { } link) + { + WriteSeparatedRow([reader.Name ?? string.Empty, row.ToString(), (column + 1).ToString(), link.Address, link.Tooltip ?? string.Empty], '\t'); + } + } + } + } + while (reader.NextResult()); + }); + return command; +} + +// ---- properties subcommand -------------------------------------------------- +static Command BuildPropertiesCommand() +{ + var fileArg = new Argument("file") { Description = "Path to the Excel file (XLS, XLSX, XLSB, XML Spreadsheet 2003)" }; + var passwordOpt = new Option("--password", ["-p"]) { Description = "Password for protected workbooks" }; + var encodingOpt = new Option("--encoding", ["-e"]) { Description = "Fallback encoding for XLS BIFF2-5 (default: windows-1252)", DefaultValueFactory = _ => "windows-1252" }; + var cmd = new Command("properties", "Show workbook document properties without reading worksheet rows"); + cmd.Arguments.Add(fileArg); + cmd.Options.Add(passwordOpt); + cmd.Options.Add(encodingOpt); + cmd.SetAction(parseResult => + { + using var stream = parseResult.GetValue(fileArg)!.OpenRead(); + using var reader = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration + { + Password = parseResult.GetValue(passwordOpt), + FallbackEncoding = Encoding.GetEncoding(parseResult.GetValue(encodingOpt)!), + SinglePassMode = true, + }); + var properties = reader.DocumentProperties; + Console.WriteLine($"Title: {properties.Title}"); + Console.WriteLine($"Subject: {properties.Subject}"); + Console.WriteLine($"Author: {properties.Author}"); + Console.WriteLine($"Keywords: {properties.Keywords}"); + Console.WriteLine($"Description: {properties.Description}"); + Console.WriteLine($"Last modified by: {properties.LastModifiedBy}"); + Console.WriteLine($"Created: {properties.Created:O}"); + Console.WriteLine($"Modified: {properties.Modified:O}"); + Console.WriteLine($"Last printed: {properties.LastPrinted:O}"); + }); + return cmd; +} + +// ---- csv subcommand --------------------------------------------------------- +static Command BuildCsvCommand() +{ + var fileArg = new Argument("file") { Description = "Path to the CSV file" }; + var noHeaderOpt = new Option("--no-header", ["-H"]) { Description = "Don't treat first row as column names" }; + var outputOpt = new Option("--output", ["-o"]) { Description = "Data output format: table, csv, tsv (default: no data output, stats only)", DefaultValueFactory = _ => OutputFormat.None }; + var encodingOpt = new Option("--encoding", ["-e"]) { Description = "Fallback encoding when no BOM / not UTF-8 (default: windows-1252)", DefaultValueFactory = _ => "windows-1252" }; + var noTrimOpt = new Option("--no-trim") { Description = "Don't trim whitespace in values" }; + var separatorsOpt = new Option("--separators") { Description = "Separator candidates as separate arguments, e.g. \",\" \";\" \"||\" -- use \\t for TAB (default: , ; TAB | #)", AllowMultipleArgumentsPerToken = true }; + var quoteCharOpt = new Option("--quote-char") { Description = "Quote character (default: \")" }; + var escapeCharOpt = new Option("--escape-char") { Description = "Escape character for quoted fields (default: disabled)" }; + var dataSetOpt = new Option("--dataset") { Description = "Use AsDataSet extension (loads all data into a DataSet in memory)" }; + var analyzeRowsOpt = new Option("--analyze-initial-rows") { Description = "Rows to analyze for CSV detection (0: entire file)" }; + var showSeparatorOpt = new Option("--show-separator") { Description = "Print the detected separator on stderr" }; + + var cmd = new Command("csv", "Read CSV files"); + cmd.Arguments.Add(fileArg); + cmd.Options.Add(noHeaderOpt); + cmd.Options.Add(outputOpt); + cmd.Options.Add(encodingOpt); + cmd.Options.Add(noTrimOpt); + cmd.Options.Add(separatorsOpt); + cmd.Options.Add(quoteCharOpt); + cmd.Options.Add(escapeCharOpt); + cmd.Options.Add(dataSetOpt); + cmd.Options.Add(analyzeRowsOpt); + cmd.Options.Add(showSeparatorOpt); + + cmd.SetAction(parseResult => + { + var file = parseResult.GetValue(fileArg)!; + var noHeader = parseResult.GetValue(noHeaderOpt); + var output = parseResult.GetValue(outputOpt); + var encodingName = parseResult.GetValue(encodingOpt)!; + var noTrim = parseResult.GetValue(noTrimOpt); + var separators = parseResult.GetValue(separatorsOpt); + var quoteCharStr = parseResult.GetValue(quoteCharOpt); + var escapeCharStr = parseResult.GetValue(escapeCharOpt); + var useDataSet = parseResult.GetValue(dataSetOpt); + + int analyzeRows = parseResult.GetValue(analyzeRowsOpt); + if (analyzeRows < 0) + throw new ArgumentException("--analyze-initial-rows must be zero or greater."); + + var config = new ExcelReaderConfiguration + { + FallbackEncoding = Encoding.GetEncoding(encodingName), + TrimWhiteSpace = !noTrim, + QuoteChar = quoteCharStr?.Length > 0 ? quoteCharStr[0] : '"', + EscapeChar = escapeCharStr?.Length > 0 ? escapeCharStr[0] : null, + AnalyzeInitialCsvRows = analyzeRows, + }; + if (separators is { Length: > 0 }) + config.AutodetectSeparators = separators.Select(separator => separator.Replace("\\t", "\t")).ToArray(); + + var memBefore = Process.GetCurrentProcess().WorkingSet64; + var sw = Stopwatch.StartNew(); + + using var stream = file.OpenRead(); + using var reader = ExcelReaderFactory.CreateCsvReader(stream, config); + + var openMs = sw.ElapsedMilliseconds; + + if (parseResult.GetValue(showSeparatorOpt)) + Console.Error.WriteLine($"Separator: {(reader.CsvSeparator is { } separator ? "\"" + separator.Replace("\t", "\\t").Replace("\r", "\\r").Replace("\n", "\\n") + "\"" : "(none)")}"); + + if (useDataSet) + { + var ds = reader.AsDataSet(new ExcelDataSetConfiguration + { + UseColumnDataType = false, + ConfigureDataTable = _ => new ExcelDataTableConfiguration + { + UseHeaderRow = !noHeader, + } + }); + + var readMs = sw.ElapsedMilliseconds - openMs; + var memAfter = Process.GetCurrentProcess().WorkingSet64; + + PrintStats(openMs, readMs, ds, memBefore, memAfter); + + if (output != OutputFormat.None) + RenderSheets(ds, output); + } + else + { + var sheets = ReadRaw(reader, noHeader, hasFilter: false, nameSet: [], indexSet: [], output); + + var readMs = sw.ElapsedMilliseconds - openMs; + var memAfter = Process.GetCurrentProcess().WorkingSet64; + + PrintRawStats(openMs, readMs, sheets, memBefore, memAfter); + } + }); + + return cmd; +} + +// ---- raw reader loop -------------------------------------------------------- +static List<(string Name, long Rows, int Cols)> ReadRaw( + IExcelDataReader reader, + bool noHeader, + bool hasFilter, + HashSet nameSet, + HashSet indexSet, + OutputFormat output) +{ + var sheets = new List<(string Name, long Rows, int Cols)>(); + bool firstOutput = true; + int sheetNumber = 0; + const int tableRowCap = 100; + + do + { + sheetNumber++; + var sheetName = reader.Name ?? string.Empty; + + if (hasFilter && !nameSet.Contains(sheetName) && !indexSet.Contains(sheetNumber)) + continue; + + long sheetRows = 0; + int sheetCols = 0; + string[]? headers = null; + List? tableBuffer = output == OutputFormat.Table ? [] : null; + + // Read header row if applicable. + if (!noHeader && reader.Read()) + { + headers = new string[reader.FieldCount]; + for (int i = 0; i < reader.FieldCount; i++) + headers[i] = reader.GetValue(i)?.ToString() ?? string.Empty; + + sheetCols = Math.Max(sheetCols, reader.FieldCount); + } + + // Emit header to separated output immediately. + if (output is OutputFormat.Csv or OutputFormat.Tsv) + { + char sep = output == OutputFormat.Csv ? ',' : '\t'; + if (!firstOutput) + Console.WriteLine(); + + if (sheets.Count > 0) + Console.WriteLine($"# Sheet: {sheetName}"); + + if (headers is not null) + WriteSeparatedRow(headers, sep); + } + + // Read data rows. + while (reader.Read()) + { + sheetRows++; + sheetCols = Math.Max(sheetCols, reader.FieldCount); + + var cells = new string[reader.FieldCount]; + for (int i = 0; i < reader.FieldCount; i++) + cells[i] = reader.GetValue(i)?.ToString() ?? string.Empty; + + if (output is OutputFormat.Csv or OutputFormat.Tsv) + WriteSeparatedRow(cells, output == OutputFormat.Csv ? ',' : '\t'); + else if (output == OutputFormat.Table && sheetRows <= tableRowCap) + tableBuffer!.Add(cells); + } + + // Render buffered table output. + if (output == OutputFormat.Table) + { + if (sheets.Count > 0) + AnsiConsole.MarkupLine($"[bold]{Markup.Escape(sheetName)}[/]"); + + if (sheetRows > tableRowCap) + Console.Error.WriteLine($"(showing first {tableRowCap:N0} of {sheetRows:N0} rows — use --output csv for full output)"); + + RenderRawTable(headers, tableBuffer!); + } + + sheets.Add((sheetName, sheetRows, sheetCols)); + firstOutput = false; + } + while (reader.NextResult()); + + return sheets; +} + +// ---- helpers ---------------------------------------------------------------- +static void PrintStats(long openMs, long readMs, DataSet ds, long memBefore, long memAfter) +{ + long totalRows = 0; + int maxCols = 0; + + foreach (DataTable dt in ds.Tables) + { + totalRows += dt.Rows.Count; + if (dt.Columns.Count > maxCols) + maxCols = dt.Columns.Count; + } + + long totalMs = openMs + readMs; + string rateStr = BuildRateStr(totalRows * maxCols, totalMs); + long memDeltaMb = (memAfter - memBefore) / (1024 * 1024); + + Console.Error.WriteLine($"Open: {openMs,6:N0} ms"); + Console.Error.Write($"Read: {readMs,6:N0} ms ({totalRows:N0} rows x {maxCols} cols"); + if (ds.Tables.Count > 1) + { + Console.Error.WriteLine($" across {ds.Tables.Count} sheets)"); + foreach (DataTable dt in ds.Tables) + Console.Error.WriteLine($" {dt.TableName}: {dt.Rows.Count:N0} rows x {dt.Columns.Count} cols"); + } + else + { + Console.Error.WriteLine(")"); + } + + Console.Error.WriteLine($"Total: {totalMs,6:N0} ms{rateStr}"); + Console.Error.WriteLine($"Memory: {(memDeltaMb >= 0 ? "+" : string.Empty)}{memDeltaMb} MB"); +} + +static void PrintRawStats(long openMs, long readMs, List<(string Name, long Rows, int Cols)> sheets, long memBefore, long memAfter) +{ + long totalRows = sheets.Sum(s => s.Rows); + int maxCols = sheets.Count > 0 ? sheets.Max(s => s.Cols) : 0; + + long totalMs = openMs + readMs; + string rateStr = BuildRateStr(totalRows * maxCols, totalMs); + long memDeltaMb = (memAfter - memBefore) / (1024 * 1024); + + Console.Error.WriteLine($"Open: {openMs,6:N0} ms"); + Console.Error.Write($"Read: {readMs,6:N0} ms ({totalRows:N0} rows x {maxCols} cols"); + if (sheets.Count > 1) + { + Console.Error.WriteLine($" across {sheets.Count} sheets)"); + foreach (var (name, rows, cols) in sheets) + Console.Error.WriteLine($" {name}: {rows:N0} rows x {cols} cols"); + } + else + { + Console.Error.WriteLine(")"); + } + + Console.Error.WriteLine($"Total: {totalMs,6:N0} ms{rateStr}"); + Console.Error.WriteLine($"Memory: {(memDeltaMb >= 0 ? "+" : string.Empty)}{memDeltaMb} MB"); +} + +static string BuildRateStr(long totalCells, long totalMs) +{ + if (totalMs <= 0) + return string.Empty; + + double cellsPerSec = totalCells * 1000.0 / totalMs; + return cellsPerSec >= 1_000_000 + ? $" (~{cellsPerSec / 1_000_000:F1}M cells/sec)" + : cellsPerSec >= 1_000 + ? $" (~{cellsPerSec / 1_000:F1}K cells/sec)" + : $" (~{cellsPerSec:F0} cells/sec)"; +} + +static void RenderSheets(DataSet ds, OutputFormat output) +{ + bool multiSheet = ds.Tables.Count > 1; + bool first = true; + + foreach (DataTable dt in ds.Tables) + { + if (output == OutputFormat.Table) + { + if (multiSheet) + AnsiConsole.MarkupLine($"[bold]{Markup.Escape(dt.TableName)}[/]"); + RenderSpectreTable(dt); + } + else + { + if (!first) + Console.WriteLine(); + if (multiSheet) + Console.WriteLine($"# Sheet: {dt.TableName}"); + WriteSeparated(dt, output == OutputFormat.Csv ? ',' : '\t'); + } + + first = false; + } +} + +static void RenderSpectreTable(DataTable dt) +{ + const int tableRowCap = 100; + var table = new Table(); + foreach (DataColumn col in dt.Columns) + table.AddColumn(Markup.Escape(col.ColumnName)); + + int rendered = 0; + foreach (DataRow row in dt.Rows) + { + if (rendered >= tableRowCap) + break; + + table.AddRow(row.ItemArray.Select(v => Markup.Escape(v?.ToString() ?? string.Empty)).ToArray()); + rendered++; + } + + if (dt.Rows.Count > tableRowCap) + Console.Error.WriteLine($"(showing first {tableRowCap:N0} of {dt.Rows.Count:N0} rows — use --output csv for full output)"); + + AnsiConsole.Write(table); +} + +static void RenderRawTable(string[]? headers, List rows) +{ + // Determine the actual maximum column count across headers and all rows. + // In single-pass mode rows may have fewer fields than the header (trailing + // empty cells are not stored), and later rows may have more columns than + // earlier ones. Pad everything to the widest row. + int colCount = headers?.Length ?? 0; + foreach (var row in rows) + colCount = Math.Max(colCount, row.Length); + + var table = new Table(); + if (headers is not null) + { + foreach (var h in headers) + table.AddColumn(Markup.Escape(h)); + + for (int i = headers.Length; i < colCount; i++) + table.AddColumn($"Col{i + 1}"); + } + else + { + for (int i = 0; i < colCount; i++) + table.AddColumn($"Col{i + 1}"); + } + + foreach (var row in rows) + { + var cells = new string[colCount]; + for (int i = 0; i < colCount; i++) + cells[i] = i < row.Length ? Markup.Escape(row[i]) : string.Empty; + + table.AddRow(cells); + } + + AnsiConsole.Write(table); +} + +static void WriteSeparated(DataTable dt, char sep) +{ + static string Escape(string s, char sep) => + s.Contains(sep) || s.Contains('"') || s.Contains('\n') || s.Contains('\r') + ? $"\"{s.Replace("\"", "\"\"")}\"" + : s; + + foreach (DataRow row in dt.Rows) + Console.WriteLine(string.Join(sep, row.ItemArray.Select(v => Escape(v?.ToString() ?? string.Empty, sep)))); +} + +static void WriteSeparatedRow(string[] cells, char sep) +{ + static string Escape(string s, char sep) => + s.Contains(sep) || s.Contains('"') || s.Contains('\n') || s.Contains('\r') + ? $"\"{s.Replace("\"", "\"\"")}\"" + : s; + + Console.WriteLine(string.Join(sep, cells.Select(v => Escape(v, sep)))); +} + +#pragma warning disable SA1649 // File name should match first type name (top-level statements use implicit Program class) +internal enum OutputFormat +{ + None, + Table, + Csv, + Tsv, +} \ No newline at end of file diff --git a/src/ExcelDataReader.DataSet/ExcelDataReader.DataSet.csproj b/src/ExcelDataReader.DataSet/ExcelDataReader.DataSet.csproj index 781af7ff..3391d982 100644 --- a/src/ExcelDataReader.DataSet/ExcelDataReader.DataSet.csproj +++ b/src/ExcelDataReader.DataSet/ExcelDataReader.DataSet.csproj @@ -11,4 +11,16 @@ + + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + diff --git a/src/ExcelDataReader.DataSet/ExcelDataReaderExtensions.cs b/src/ExcelDataReader.DataSet/ExcelDataReaderExtensions.cs index 1598420d..952697fc 100644 --- a/src/ExcelDataReader.DataSet/ExcelDataReaderExtensions.cs +++ b/src/ExcelDataReader.DataSet/ExcelDataReaderExtensions.cs @@ -1,4 +1,5 @@ using System.Data; +using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace ExcelDataReader; @@ -14,7 +15,7 @@ public static class ExcelDataReaderExtensions /// The IExcelDataReader instance. /// An optional configuration object to modify the behavior of the conversion. /// A dataset with all workbook contents. - public static DataSet AsDataSet(this IExcelDataReader self, ExcelDataSetConfiguration configuration = null) + public static DataSet AsDataSet(this IExcelDataReader self, ExcelDataSetConfiguration? configuration = null) { configuration ??= new(); @@ -68,13 +69,26 @@ private static string GetUniqueColumnName(DataTable table, string name) private static DataTable AsDataTable(IExcelDataReader self, ExcelDataTableConfiguration configuration) { - var result = new DataTable { TableName = self.Name }; + var result = new DataTable { TableName = self.Name, CaseSensitive = configuration.CaseSensitive }; result.ExtendedProperties.Add("visiblestate", self.VisibleState); var first = true; var emptyRows = 0; - List columnIndices = []; + List mergedCellsList = []; + Dictionary<(int Row, int Column), object?> mergeCellValue = []; + + // If need to fill merged cells, check the next row have merged cells + var nextRowHaveMergedCell = false; + if (configuration.FillMergedCellsValue) + { + mergedCellsList = self.MergeCells.OrderBy(c => c.FromRow).ThenBy(c => c.FromColumn).ToList(); + } + + int rowIndex = -1; + int lastCheckedFieldCount = 0; + List columnIndices = new(self.FieldCount); while (self.Read()) { + rowIndex++; if (first) { if (configuration.UseHeaderRow && configuration.ReadHeaderRow != null) @@ -82,7 +96,7 @@ private static DataTable AsDataTable(IExcelDataReader self, ExcelDataTableConfig configuration.ReadHeaderRow(self); } - if (configuration.ReadHeader != null) + if (configuration.ReadHeader != null) { var dict = configuration.ReadHeader(self); foreach (var kvp in dict) @@ -96,8 +110,8 @@ private static DataTable AsDataTable(IExcelDataReader self, ExcelDataTableConfig result.Columns.Add(column); columnIndices.Add(columnIndex); } - } - else + } + else { for (var i = 0; i < self.FieldCount; i++) { @@ -107,8 +121,8 @@ private static DataTable AsDataTable(IExcelDataReader self, ExcelDataTableConfig } var name = configuration.UseHeaderRow - ? Convert.ToString(self.GetValue(i), CultureInfo.CurrentCulture) - : null; + ? Convert.ToString(self.GetValue(i), CultureInfo.CurrentCulture) ?? string.Empty + : string.Empty; if (string.IsNullOrEmpty(name)) { @@ -124,6 +138,7 @@ private static DataTable AsDataTable(IExcelDataReader self, ExcelDataTableConfig } result.BeginLoadData(); + lastCheckedFieldCount = self.FieldCount; first = false; if (configuration.UseHeaderRow) @@ -131,13 +146,33 @@ private static DataTable AsDataTable(IExcelDataReader self, ExcelDataTableConfig continue; } } + else if (configuration.ReadHeader == null && self.FieldCount > lastCheckedFieldCount) + { + // Grow DataTable columns dynamically when FieldCount increases (e.g. single-pass mode) + for (var i = lastCheckedFieldCount; i < self.FieldCount; i++) + { + if (configuration.FilterColumn != null && !configuration.FilterColumn(self, i)) + { + continue; + } + + var name = configuration.EmptyColumnNamePrefix + i; + var columnName = GetUniqueColumnName(result, name); + var column = new DataColumn(columnName, typeof(object)) { Caption = name }; + result.Columns.Add(column); + columnIndices.Add(i); + } + + lastCheckedFieldCount = self.FieldCount; + } if (configuration.FilterRow != null && !configuration.FilterRow(self)) { continue; } - if (IsEmptyRow(self, configuration)) + // if next row is containing merged cells, skip the empty row check + if (!nextRowHaveMergedCell && IsEmptyRow(self, configuration)) { emptyRows++; continue; @@ -157,9 +192,49 @@ private static DataTable AsDataTable(IExcelDataReader self, ExcelDataTableConfig var columnIndex = columnIndices[i]; var value = self.GetValue(columnIndex); + if (configuration.FillMergedCellsValue) + { + CellRange? range = null; + foreach (var candidate in mergedCellsList) + { + if (candidate.FromRow > rowIndex) + break; + + if (candidate.FromRow <= rowIndex && candidate.ToRow >= rowIndex && + candidate.FromColumn <= columnIndex && candidate.ToColumn >= columnIndex) + { + range = candidate; + break; + } + } + + if (range != null) + { + if (mergeCellValue.TryGetValue((range.FromRow, range.FromColumn), out var mergedValue)) + { + value = mergedValue; + } + else + { + mergeCellValue[(range.FromRow, range.FromColumn)] = value; + } + + // mark next row is in merged range, skip empty row check and to fill row + if (rowIndex < range.ToRow) + { + nextRowHaveMergedCell = true; + } + else if (rowIndex == range.ToRow && columnIndex == range.ToColumn) + { + mergedCellsList.Remove(range); + nextRowHaveMergedCell = false; + } + } + } + if (configuration.TransformValue != null) { - var transformedValue = configuration.TransformValue(self, i, value); + var transformedValue = configuration.TransformValue(self, i, value is DBNull ? null : value); if (transformedValue != null) value = transformedValue; } @@ -181,18 +256,23 @@ private static bool IsEmptyRow(IExcelDataReader reader, ExcelDataTableConfigurat var value = reader.GetValue(i); if (configuration.TransformValue != null) { - var transformedValue = configuration.TransformValue(reader, i, value); + var transformedValue = configuration.TransformValue(reader, i, value is DBNull ? null : value); if (transformedValue != null) value = transformedValue; } - if (value != null) + if (value != null && value is not DBNull) return false; } return true; } + // DataColumn.DataType setter requires [DynamicallyAccessedMembers] but the type comes from GetType() on + // values written by ExcelDataReader (string, double, DateTime, etc.) — always available at runtime. +#if NET5_0_OR_GREATER + [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "Types returned by GetType() on ExcelDataReader output values are always fully available at runtime.")] +#endif private static void FixDataTypes(DataSet dataset) { var tables = new List(dataset.Tables.Count); @@ -205,10 +285,11 @@ private static void FixDataTypes(DataSet dataset) continue; } - DataTable newTable = null; + DataTable? newTable = null; + Columns: for (int i = 0; i < table.Columns.Count; i++) { - Type type = null; + Type? type = null; foreach (DataRow row in table.Rows) { if (row.IsNull(i)) @@ -222,8 +303,7 @@ private static void FixDataTypes(DataSet dataset) } else { - type = null; - break; + continue Columns; } } } @@ -258,4 +338,4 @@ private static void FixDataTypes(DataSet dataset) dataset.Tables.AddRange(tables.ToArray()); } } -} +} \ No newline at end of file diff --git a/src/ExcelDataReader.DataSet/ExcelDataSetConfiguration.cs b/src/ExcelDataReader.DataSet/ExcelDataSetConfiguration.cs index 940eccb2..d179ff1a 100644 --- a/src/ExcelDataReader.DataSet/ExcelDataSetConfiguration.cs +++ b/src/ExcelDataReader.DataSet/ExcelDataSetConfiguration.cs @@ -13,10 +13,10 @@ public class ExcelDataSetConfiguration /// /// Gets or sets a callback to obtain configuration options for a DataTable. /// - public Func ConfigureDataTable { get; set; } + public Func? ConfigureDataTable { get; set; } /// /// Gets or sets a callback to determine whether to include the current sheet in the DataSet. Called once per sheet before ConfigureDataTable. /// - public Func FilterSheet { get; set; } + public Func? FilterSheet { get; set; } } diff --git a/src/ExcelDataReader.DataSet/ExcelDataTableConfiguration.cs b/src/ExcelDataReader.DataSet/ExcelDataTableConfiguration.cs index 04243d4f..c49c46d9 100644 --- a/src/ExcelDataReader.DataSet/ExcelDataTableConfiguration.cs +++ b/src/ExcelDataReader.DataSet/ExcelDataTableConfiguration.cs @@ -5,6 +5,11 @@ namespace ExcelDataReader; /// public class ExcelDataTableConfiguration { + /// + /// Gets or sets a value indicating whether the DataTable should be case sensitive. Useful when setting a primary key after loading from Excel. + /// + public bool CaseSensitive { get; set; } + /// /// Gets or sets a value indicating the prefix of generated column names. /// @@ -18,7 +23,7 @@ public class ExcelDataTableConfiguration /// /// Gets or sets a callback to determine which row is the header row. Only called when UseHeaderRow = true. /// - public Action ReadHeaderRow { get; set; } + public Action? ReadHeaderRow { get; set; } /// /// Gets or sets a callback to allow a custom implementation of header reading. @@ -27,20 +32,25 @@ public class ExcelDataTableConfiguration /// An example use of this would be to combine multiple header rows. /// NOTE: If this field is set, UseHeaderRow, EmptyColumnNamePrefix, and FilterColumn are ignored. /// - public Func> ReadHeader { get; set; } + public Func>? ReadHeader { get; set; } /// /// Gets or sets a callback to determine whether to include the current row in the DataTable. /// - public Func FilterRow { get; set; } + public Func? FilterRow { get; set; } /// /// Gets or sets a callback to determine whether to include the specific column in the DataTable. Called once per column after reading the headers. /// - public Func FilterColumn { get; set; } + public Func? FilterColumn { get; set; } /// /// Gets or sets a callback to determine whether to transform the cell value. /// - public Func TransformValue { get; set; } + public Func? TransformValue { get; set; } + + /// + /// Gets or sets a value indicating whether merged cells should be filled with their top-left cell's value. + /// + public bool FillMergedCellsValue { get; set; } } diff --git a/src/ExcelDataReader.DataSet/packages.lock.json b/src/ExcelDataReader.DataSet/packages.lock.json index 684cac8a..c6f2fb5a 100644 --- a/src/ExcelDataReader.DataSet/packages.lock.json +++ b/src/ExcelDataReader.DataSet/packages.lock.json @@ -1,5 +1,5 @@ { - "version": 1, + "version": 2, "dependencies": { ".NETFramework,Version=v4.6.2": { "Microsoft.NETFramework.ReferenceAssemblies": { @@ -11,30 +11,17 @@ "Microsoft.NETFramework.ReferenceAssemblies.net462": "1.0.3" } }, - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[8.0.0, )", - "resolved": "8.0.0", - "contentHash": "G5q7OqtwIyGTkeIOAc3u2ZuV/kicQaec5EaRnc0pIeSnh9LUjj+PYQrJYBURvDt7twGl2PKA7nSN0kz1Zw5bnQ==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "8.0.0", - "Microsoft.SourceLink.Common": "8.0.0" - } - }, "PolySharp": { "type": "Direct", - "requested": "[1.15.0, )", - "resolved": "1.15.0", - "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" + "requested": "[1.17.1, )", + "resolved": "1.17.1", + "contentHash": "Fv7mkMwEqA3vR03wey85rWT7UdJqC5jN2GrkzRondHpAfVTYoKtlh2Aun0ZVMijAo4Ijhi3PT2yWYgg9VC2f9A==" }, "StyleCop.Analyzers": { "type": "Direct", - "requested": "[1.2.0-beta.556, )", - "resolved": "1.2.0-beta.556", - "contentHash": "llRPgmA1fhC0I0QyFLEcjvtM2239QzKr/tcnbsjArLMJxJlu0AA5G7Fft0OI30pHF3MW63Gf4aSSsjc5m82J1Q==", - "dependencies": { - "StyleCop.Analyzers.Unstable": "1.2.0.556" - } + "requested": "[1.3.180, )", + "resolved": "1.3.180", + "contentHash": "/TDyrO3tUJOsnyTazvaX+qwwBt4aixQLNLtxmkyWQZE94IOZ9PnClHrwKUVn/NSXdXUUWrKMHTtlxUkZ1F8JWg==" }, "System.ValueTuple": { "type": "Direct", @@ -42,44 +29,46 @@ "resolved": "4.5.0", "contentHash": "okurQJO6NRE/apDIP23ajJ0hpiNmJ+f0BwOlB/cSqTLQlw5upkf+5+96+iG2Jw40G1fCVCyPz/FhIABUjMR+RQ==" }, - "Microsoft.Build.Tasks.Git": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "bZKfSIKJRXLTuSzLudMFte/8CempWjVamNUR5eHJizsy+iuOuO/k2gnh7W0dHJmYY0tBf+gUErfluCv5mySAOQ==" - }, "Microsoft.NETFramework.ReferenceAssemblies.net462": { "type": "Transitive", "resolved": "1.0.3", "contentHash": "IzAV30z22ESCeQfxP29oVf4qEo8fBGXLXSU6oacv/9Iqe6PzgHDKCaWfwMBak7bSJQM0F5boXWoZS+kChztRIQ==" }, - "Microsoft.SourceLink.Common": { + "System.Buffers": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" + }, + "System.Numerics.Vectors": { "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "dk9JPxTCIevS75HyEQ0E4OVAFhB2N+V9ShCXf8Q6FkUQZDkgLI12y679Nym1YqsiSysuQskT7Z+6nUf3yab6Vw==" + "resolved": "4.6.1", + "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" }, - "StyleCop.Analyzers.Unstable": { + "System.Runtime.CompilerServices.Unsafe": { "type": "Transitive", - "resolved": "1.2.0.556", - "contentHash": "zvn9Mqs/ox/83cpYPignI8hJEM2A93s2HkHs8HYMOAQW0PkampyoErAiIyKxgTLqbbad29HX/shv/6LGSjPJNQ==" + "resolved": "6.1.2", + "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" }, "exceldatareader": { "type": "Project", "dependencies": { + "System.Memory": "[4.6.3, )", "System.ValueTuple": "[4.5.0, )" } + }, + "System.Memory": { + "type": "CentralTransitive", + "requested": "[4.6.3, )", + "resolved": "4.6.3", + "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Numerics.Vectors": "4.6.1", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } } }, ".NETStandard,Version=v2.0": { - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[8.0.0, )", - "resolved": "8.0.0", - "contentHash": "G5q7OqtwIyGTkeIOAc3u2ZuV/kicQaec5EaRnc0pIeSnh9LUjj+PYQrJYBURvDt7twGl2PKA7nSN0kz1Zw5bnQ==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "8.0.0", - "Microsoft.SourceLink.Common": "8.0.0" - } - }, "NETStandard.Library": { "type": "Direct", "requested": "[2.0.3, )", @@ -91,128 +80,83 @@ }, "PolySharp": { "type": "Direct", - "requested": "[1.15.0, )", - "resolved": "1.15.0", - "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" + "requested": "[1.17.1, )", + "resolved": "1.17.1", + "contentHash": "Fv7mkMwEqA3vR03wey85rWT7UdJqC5jN2GrkzRondHpAfVTYoKtlh2Aun0ZVMijAo4Ijhi3PT2yWYgg9VC2f9A==" }, "StyleCop.Analyzers": { "type": "Direct", - "requested": "[1.2.0-beta.556, )", - "resolved": "1.2.0-beta.556", - "contentHash": "llRPgmA1fhC0I0QyFLEcjvtM2239QzKr/tcnbsjArLMJxJlu0AA5G7Fft0OI30pHF3MW63Gf4aSSsjc5m82J1Q==", - "dependencies": { - "StyleCop.Analyzers.Unstable": "1.2.0.556" - } - }, - "Microsoft.Build.Tasks.Git": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "bZKfSIKJRXLTuSzLudMFte/8CempWjVamNUR5eHJizsy+iuOuO/k2gnh7W0dHJmYY0tBf+gUErfluCv5mySAOQ==" + "requested": "[1.3.180, )", + "resolved": "1.3.180", + "contentHash": "/TDyrO3tUJOsnyTazvaX+qwwBt4aixQLNLtxmkyWQZE94IOZ9PnClHrwKUVn/NSXdXUUWrKMHTtlxUkZ1F8JWg==" }, "Microsoft.NETCore.Platforms": { "type": "Transitive", "resolved": "1.1.0", "contentHash": "kz0PEW2lhqygehI/d6XsPCQzD7ff7gUJaVGPVETX611eadGsA3A877GdSlU0LRVMCTH/+P3o2iDTak+S08V2+A==" }, - "Microsoft.SourceLink.Common": { + "System.Buffers": { "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "dk9JPxTCIevS75HyEQ0E4OVAFhB2N+V9ShCXf8Q6FkUQZDkgLI12y679Nym1YqsiSysuQskT7Z+6nUf3yab6Vw==" + "resolved": "4.6.1", + "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" }, - "StyleCop.Analyzers.Unstable": { + "System.Numerics.Vectors": { "type": "Transitive", - "resolved": "1.2.0.556", - "contentHash": "zvn9Mqs/ox/83cpYPignI8hJEM2A93s2HkHs8HYMOAQW0PkampyoErAiIyKxgTLqbbad29HX/shv/6LGSjPJNQ==" + "resolved": "4.6.1", + "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" + }, + "System.Runtime.CompilerServices.Unsafe": { + "type": "Transitive", + "resolved": "6.1.2", + "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" }, "exceldatareader": { - "type": "Project" - } - }, - ".NETStandard,Version=v2.1": { - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[8.0.0, )", - "resolved": "8.0.0", - "contentHash": "G5q7OqtwIyGTkeIOAc3u2ZuV/kicQaec5EaRnc0pIeSnh9LUjj+PYQrJYBURvDt7twGl2PKA7nSN0kz1Zw5bnQ==", + "type": "Project", "dependencies": { - "Microsoft.Build.Tasks.Git": "8.0.0", - "Microsoft.SourceLink.Common": "8.0.0" + "System.Memory": "[4.6.3, )" } }, + "System.Memory": { + "type": "CentralTransitive", + "requested": "[4.6.3, )", + "resolved": "4.6.3", + "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Numerics.Vectors": "4.6.1", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + } + }, + ".NETStandard,Version=v2.1": { "PolySharp": { "type": "Direct", - "requested": "[1.15.0, )", - "resolved": "1.15.0", - "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" + "requested": "[1.17.1, )", + "resolved": "1.17.1", + "contentHash": "Fv7mkMwEqA3vR03wey85rWT7UdJqC5jN2GrkzRondHpAfVTYoKtlh2Aun0ZVMijAo4Ijhi3PT2yWYgg9VC2f9A==" }, "StyleCop.Analyzers": { "type": "Direct", - "requested": "[1.2.0-beta.556, )", - "resolved": "1.2.0-beta.556", - "contentHash": "llRPgmA1fhC0I0QyFLEcjvtM2239QzKr/tcnbsjArLMJxJlu0AA5G7Fft0OI30pHF3MW63Gf4aSSsjc5m82J1Q==", - "dependencies": { - "StyleCop.Analyzers.Unstable": "1.2.0.556" - } - }, - "Microsoft.Build.Tasks.Git": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "bZKfSIKJRXLTuSzLudMFte/8CempWjVamNUR5eHJizsy+iuOuO/k2gnh7W0dHJmYY0tBf+gUErfluCv5mySAOQ==" - }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "dk9JPxTCIevS75HyEQ0E4OVAFhB2N+V9ShCXf8Q6FkUQZDkgLI12y679Nym1YqsiSysuQskT7Z+6nUf3yab6Vw==" - }, - "StyleCop.Analyzers.Unstable": { - "type": "Transitive", - "resolved": "1.2.0.556", - "contentHash": "zvn9Mqs/ox/83cpYPignI8hJEM2A93s2HkHs8HYMOAQW0PkampyoErAiIyKxgTLqbbad29HX/shv/6LGSjPJNQ==" + "requested": "[1.3.180, )", + "resolved": "1.3.180", + "contentHash": "/TDyrO3tUJOsnyTazvaX+qwwBt4aixQLNLtxmkyWQZE94IOZ9PnClHrwKUVn/NSXdXUUWrKMHTtlxUkZ1F8JWg==" }, "exceldatareader": { "type": "Project" } }, - "net8.0": { - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[8.0.0, )", - "resolved": "8.0.0", - "contentHash": "G5q7OqtwIyGTkeIOAc3u2ZuV/kicQaec5EaRnc0pIeSnh9LUjj+PYQrJYBURvDt7twGl2PKA7nSN0kz1Zw5bnQ==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "8.0.0", - "Microsoft.SourceLink.Common": "8.0.0" - } - }, + "net10.0": { "PolySharp": { "type": "Direct", - "requested": "[1.15.0, )", - "resolved": "1.15.0", - "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" + "requested": "[1.17.1, )", + "resolved": "1.17.1", + "contentHash": "Fv7mkMwEqA3vR03wey85rWT7UdJqC5jN2GrkzRondHpAfVTYoKtlh2Aun0ZVMijAo4Ijhi3PT2yWYgg9VC2f9A==" }, "StyleCop.Analyzers": { "type": "Direct", - "requested": "[1.2.0-beta.556, )", - "resolved": "1.2.0-beta.556", - "contentHash": "llRPgmA1fhC0I0QyFLEcjvtM2239QzKr/tcnbsjArLMJxJlu0AA5G7Fft0OI30pHF3MW63Gf4aSSsjc5m82J1Q==", - "dependencies": { - "StyleCop.Analyzers.Unstable": "1.2.0.556" - } - }, - "Microsoft.Build.Tasks.Git": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "bZKfSIKJRXLTuSzLudMFte/8CempWjVamNUR5eHJizsy+iuOuO/k2gnh7W0dHJmYY0tBf+gUErfluCv5mySAOQ==" - }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "dk9JPxTCIevS75HyEQ0E4OVAFhB2N+V9ShCXf8Q6FkUQZDkgLI12y679Nym1YqsiSysuQskT7Z+6nUf3yab6Vw==" - }, - "StyleCop.Analyzers.Unstable": { - "type": "Transitive", - "resolved": "1.2.0.556", - "contentHash": "zvn9Mqs/ox/83cpYPignI8hJEM2A93s2HkHs8HYMOAQW0PkampyoErAiIyKxgTLqbbad29HX/shv/6LGSjPJNQ==" + "requested": "[1.3.180, )", + "resolved": "1.3.180", + "contentHash": "/TDyrO3tUJOsnyTazvaX+qwwBt4aixQLNLtxmkyWQZE94IOZ9PnClHrwKUVn/NSXdXUUWrKMHTtlxUkZ1F8JWg==" }, "exceldatareader": { "type": "Project" diff --git a/src/ExcelDataReader.NoProvider.Tests/ExcelDataReader.NoProvider.Tests.csproj b/src/ExcelDataReader.NoProvider.Tests/ExcelDataReader.NoProvider.Tests.csproj new file mode 100644 index 00000000..59f7c165 --- /dev/null +++ b/src/ExcelDataReader.NoProvider.Tests/ExcelDataReader.NoProvider.Tests.csproj @@ -0,0 +1,24 @@ + + + net10.0;net11.0 + true + + + + + + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + diff --git a/src/ExcelDataReader.NoProvider.Tests/NoProviderTests.cs b/src/ExcelDataReader.NoProvider.Tests/NoProviderTests.cs new file mode 100644 index 00000000..a60ff80a --- /dev/null +++ b/src/ExcelDataReader.NoProvider.Tests/NoProviderTests.cs @@ -0,0 +1,387 @@ +using System.Runtime.Versioning; +using System.Text; +using ExcelDataReader.Tests; + +namespace ExcelDataReader.NoProvider.Tests; + +public class NoProviderTests +{ + [Test] + public void UsesExpectedLibraryAsset() + { + string framework = typeof(ExcelReaderFactory).Assembly.GetCustomAttributes(typeof(TargetFrameworkAttribute), false) + .Cast().Single().FrameworkName; +#if NET10_0 + Assert.That(framework, Is.EqualTo(".NETStandard,Version=v2.0")); +#else + Assert.That(framework, Is.EqualTo(".NETCoreApp,Version=v10.0")); +#endif + } + + [TestCase("10x10.xlsx", false, false)] + [TestCase("10x10.xlsx", false, true)] + [TestCase("10x10.xlsx", true, false)] + [TestCase("10x10.xlsx", true, true)] + [TestCase("10x10.xlsb", false, false)] + [TestCase("10x10.xlsb", false, true)] + [TestCase("10x10.xls", false, false)] + [TestCase("10x10.xls", false, true)] + [TestCase("10x10.xml", false, false)] + [TestCase("10x10.xml", false, true)] + public void ReadsUnicodeWorkbooksWithoutRegisteringProvider(string file, bool strict, bool singlePass) + { + AssertProviderNotRegistered(); + using var stream = TestWorkbook.Open(strict ? Path.Combine("strict", file) : file); + using var reader = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration { SinglePassMode = singlePass }); + Assert.That(reader.Read(), Is.True); + AssertProviderNotRegistered(); + } + + [Test] + public void ReadsUtf8CsvWithoutRegisteringProvider() + { + AssertProviderNotRegistered(); + using var stream = new MemoryStream(Encoding.UTF8.GetBytes("a,b\n")); + using var reader = ExcelReaderFactory.CreateCsvReader(stream); + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("a")); + AssertProviderNotRegistered(); + } + + [Test] + public void LegacyCsvFallbackWithoutRegisteringProvider() + { + AssertProviderNotRegistered(); + using var stream = new MemoryStream([0xE9, (byte)',', (byte)'b', (byte)'\n']); +#if NET10_0 + Assert.Throws(() => ExcelReaderFactory.CreateCsvReader(stream)); +#else + using var reader = ExcelReaderFactory.CreateCsvReader(stream); + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("\u00e9")); +#endif + AssertProviderNotRegistered(); + } + + [Test] + public void IncompleteUtf8CsvUsesFallbackWithoutRegisteringProvider() + { + AssertProviderNotRegistered(); + using var stream = new MemoryStream([0xe9]); +#if NET10_0 + Assert.Throws(() => ExcelReaderFactory.CreateCsvReader(stream)); +#else + using var reader = ExcelReaderFactory.CreateCsvReader(stream); + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("\u00e9")); +#endif + AssertProviderNotRegistered(); + } + + [TestCase(false)] + [TestCase(true)] + public void ReadsBiff2WithDeclaredUtf8WithoutRegisteringProvider(bool singlePass) + { + AssertProviderNotRegistered(); + using var stream = CreateBiff2(65001); + using var reader = ExcelReaderFactory.CreateBinaryReader(stream, new ExcelReaderConfiguration { SinglePassMode = singlePass }); + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("A")); + reader.Reset(); + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("A")); + AssertProviderNotRegistered(); + } + + [TestCase(false)] + [TestCase(true)] + public void Biff2WithoutCodePageUsesConfiguredFallback(bool singlePass) + { + AssertProviderNotRegistered(); + using var stream = CreateBiff2(null); + var configuration = new ExcelReaderConfiguration { SinglePassMode = singlePass, FallbackEncoding = Encoding.UTF8 }; + using var reader = ExcelReaderFactory.CreateBinaryReader(stream, configuration); + configuration.FallbackEncoding = Encoding.Unicode; + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("A")); + AssertProviderNotRegistered(); + } + + [TestCase(false)] + [TestCase(true)] + public void ReadsBiff5WithDeclaredUtf8WithoutRegisteringProvider(bool singlePass) + { + AssertProviderNotRegistered(); + using var stream = CreateBiff5(); + using var reader = ExcelReaderFactory.CreateBinaryReader(stream, new ExcelReaderConfiguration { SinglePassMode = singlePass }); + Assert.That(reader.Name, Is.EqualTo("S")); + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("A")); + reader.Reset(); + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("A")); + AssertProviderNotRegistered(); + } + + [TestCase(false)] + [TestCase(true)] + public void Biff2WithoutCodePageResolvesDefaultOnlyWhenNeeded(bool singlePass) + { + AssertProviderNotRegistered(); + using var stream = CreateBiff2(null); + var configuration = new ExcelReaderConfiguration { SinglePassMode = singlePass }; + using var reader = ExcelReaderFactory.CreateBinaryReader(stream, configuration); +#if NET10_0 + Assert.Throws(() => reader.Read()); +#else + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("A")); +#endif + AssertProviderNotRegistered(); + } + + [TestCase(false)] + [TestCase(true)] + public void ReadsBiff8FormulaStringsWithoutRegisteringProvider(bool singlePass) + { + AssertProviderNotRegistered(); + using var stream = TestWorkbook.Open("Hyperlinks.xls"); + using var reader = ExcelReaderFactory.CreateBinaryReader(stream, new ExcelReaderConfiguration { SinglePassMode = singlePass }); + for (int row = 0; row <= 10; row++) + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("Formula label")); + reader.Reset(); + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("Website fragment")); + AssertProviderNotRegistered(); + } + + [TestCase(0x0204, false)] + [TestCase(0x0204, true)] + [TestCase(0x00d6, false)] + [TestCase(0x00d6, true)] + public void ReadsBiff8InlineStringsWithoutRegisteringProvider(int recordId, bool singlePass) + { + AssertProviderNotRegistered(); + using var stream = CreateBiff8InlineString((ushort)recordId); + using var reader = ExcelReaderFactory.CreateBinaryReader(stream, new ExcelReaderConfiguration { SinglePassMode = singlePass }); + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("\u03bb")); + reader.Reset(); + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo("\u03bb")); + AssertProviderNotRegistered(); + } + + [TestCase("url", false)] + [TestCase("url", true)] + [TestCase("unicodeFile", false)] + [TestCase("unicodeFile", true)] + public void ReadsBiff8UnicodeHyperlinksWithoutRegisteringProvider(string kind, bool singlePass) + { + AssertProviderNotRegistered(); + using var stream = CreateBiff8Hyperlink(kind); + using var reader = ExcelReaderFactory.CreateBinaryReader(stream, new ExcelReaderConfiguration { SinglePassMode = singlePass }); + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetHyperlink(0)?.Address, Is.EqualTo(kind == "url" ? "https://example.com/" : "\u5831\u544a.xlsx")); + AssertProviderNotRegistered(); + } + + [TestCase(false)] + [TestCase(true)] + public void Biff8AnsiHyperlinkStillRequiresCodePage(bool singlePass) + { + AssertProviderNotRegistered(); + using var stream = CreateBiff8Hyperlink("ansiFile"); + using var reader = ExcelReaderFactory.CreateBinaryReader(stream, new ExcelReaderConfiguration { SinglePassMode = singlePass }); + Assert.That(reader.Read(), Is.True); +#if NET10_0 + Assert.Throws(() => reader.GetHyperlink(0)); +#else + Assert.That(reader.GetHyperlink(0)?.Address, Is.EqualTo("caf\u00e9.xls")); +#endif + AssertProviderNotRegistered(); + } + + private static void AssertProviderNotRegistered() + { + Assert.Throws(() => Encoding.GetEncoding(1252)); + } + + private static MemoryStream CreateBiff2(ushort? codePage) + { + var stream = new MemoryStream(); + using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)) + { + writer.Write((ushort)0x09); + writer.Write((ushort)4); + writer.Write((ushort)2); + writer.Write((ushort)0x10); + if (codePage.HasValue) + { + writer.Write((ushort)0x42); + writer.Write((ushort)2); + writer.Write(codePage.Value); + } + + writer.Write((ushort)0x04); + writer.Write((ushort)9); + writer.Write((ushort)0); + writer.Write((ushort)0); + writer.Write(new byte[3]); + writer.Write((byte)1); + writer.Write((byte)'A'); + writer.Write((ushort)0x0A); + writer.Write((ushort)0); + } + + stream.Position = 0; + return stream; + } + + private static MemoryStream CreateBiff5() + { + var stream = new MemoryStream(); + using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)) + { + writer.Write((ushort)0x0809); + writer.Write((ushort)4); + writer.Write((ushort)0x0500); + writer.Write((ushort)0x0005); + writer.Write((ushort)0x0085); + writer.Write((ushort)8); + writer.Write(30U); + writer.Write((ushort)0); + writer.Write((byte)1); + writer.Write((byte)'S'); + writer.Write((ushort)0x0042); + writer.Write((ushort)2); + writer.Write((ushort)65001); + writer.Write((ushort)0x000A); + writer.Write((ushort)0); + writer.Write((ushort)0x0809); + writer.Write((ushort)4); + writer.Write((ushort)0x0500); + writer.Write((ushort)0x0010); + writer.Write((ushort)0x0204); + writer.Write((ushort)9); + writer.Write((ushort)0); + writer.Write((ushort)0); + writer.Write((ushort)0); + writer.Write((ushort)1); + writer.Write((byte)'A'); + writer.Write((ushort)0x000A); + writer.Write((ushort)0); + } + + stream.Position = 0; + return stream; + } + + private static MemoryStream CreateBiff8InlineString(ushort recordId) + { + var stream = new MemoryStream(); + using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)) + { + BiffRecord(writer, 0x0809, data => + { + data.Write((ushort)0x0600); + data.Write((ushort)5); + }); + BiffRecord(writer, 0x0085, data => + { + data.Write(42U); + data.Write((ushort)0); + data.Write((byte)1); + data.Write((byte)0); + data.Write((byte)'S'); + }); + BiffRecord(writer, 0x0031, data => data.Write(new byte[13])); + BiffRecord(writer, 0x000a, _ => { }); + BiffRecord(writer, 0x0809, data => + { + data.Write((ushort)0x0600); + data.Write((ushort)0x10); + }); + BiffRecord(writer, recordId, data => + { + data.Write((ushort)0); + data.Write((ushort)0); + data.Write((ushort)0); + data.Write((ushort)1); + data.Write((byte)1); + data.Write((ushort)0x03bb); + }); + BiffRecord(writer, 0x000a, _ => { }); + } + + stream.Position = 0; + return stream; + } + + private static MemoryStream CreateBiff8Hyperlink(string kind) + { + var stream = new MemoryStream(); + using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)) + { + BiffRecord(writer, 0x0809, data => + { + data.Write((ushort)0x0600); + data.Write((ushort)0x10); + }); + BiffRecord(writer, 0x0203, data => + { + data.Write((ushort)0); + data.Write((ushort)0); + data.Write((ushort)0); + data.Write(42.0); + }); + BiffRecord(writer, 0x01b8, data => + { + data.Write(new byte[8]); + data.Write(new Guid("79EAC9D0-BAF9-11CE-8C82-00AA004BA90B").ToByteArray()); + data.Write(2); + data.Write(1); + data.Write(new Guid(kind == "url" ? "79EAC9E0-BAF9-11CE-8C82-00AA004BA90B" : "00000303-0000-0000-C000-000000000046").ToByteArray()); + if (kind == "url") + { + byte[] url = Encoding.Unicode.GetBytes("https://example.com/\0"); + data.Write(url.Length); + data.Write(url); + } + else + { + byte[] ansi = [(byte)'c', (byte)'a', (byte)'f', 0xe9, (byte)'.', (byte)'x', (byte)'l', (byte)'s', 0]; + data.Write((ushort)0); + data.Write(ansi.Length); + data.Write(ansi); + data.Write(ushort.MaxValue); + data.Write((ushort)0xdead); + data.Write(new byte[20]); + byte[] unicode = kind == "unicodeFile" ? Encoding.Unicode.GetBytes("\u5831\u544a.xlsx") : []; + data.Write(unicode.Length == 0 ? 0 : unicode.Length + 6); + if (unicode.Length != 0) + { + data.Write(unicode.Length); + data.Write((ushort)3); + data.Write(unicode); + } + } + }); + BiffRecord(writer, 0x000a, _ => { }); + } + + stream.Position = 0; + return stream; + } + + private static void BiffRecord(BinaryWriter writer, ushort id, Action write) + { + using var payload = new MemoryStream(); + using (var data = new BinaryWriter(payload, Encoding.UTF8, leaveOpen: true)) + write(data); + writer.Write(id); + writer.Write((ushort)payload.Length); + writer.Write(payload.ToArray()); + } +} diff --git a/src/ExcelDataReader.NoProvider.Tests/packages.lock.json b/src/ExcelDataReader.NoProvider.Tests/packages.lock.json new file mode 100644 index 00000000..3f60f918 --- /dev/null +++ b/src/ExcelDataReader.NoProvider.Tests/packages.lock.json @@ -0,0 +1,243 @@ +{ + "version": 1, + "dependencies": { + "net10.0": { + "Microsoft.NET.Test.Sdk": { + "type": "Direct", + "requested": "[18.12.0, )", + "resolved": "18.12.0", + "contentHash": "MdVkskM2ZCKSlNts5DIbz9MZidX7SwcXKBoBqY4XT91b30hAwC8PkjWbdGKRak6BKAD1BQqaZnh/SD0AJGoDCQ==", + "dependencies": { + "Microsoft.CodeCoverage": "18.12.0", + "Microsoft.TestPlatform.TestHost": "18.12.0" + } + }, + "NUnit": { + "type": "Direct", + "requested": "[5.0.0, )", + "resolved": "5.0.0", + "contentHash": "tW5Juazgh4CI4pXo5c9c2J9J4i9vwZMm/FJ+gRRe0plJHLCz7Ck/raPuE5q1xWmLAUwpao4Ht1Uy1uRN3Wo5sw==" + }, + "NUnit.Analyzers": { + "type": "Direct", + "requested": "[4.15.0, )", + "resolved": "4.15.0", + "contentHash": "WbZpZI/gmrmTcb8JnP8poJBD4V6hJs2RRIQAmNxQ763t7RktZ/d6xxuU08XAd4K6SpnF0Bm02ADqL2wZ0CNIQA==" + }, + "NUnit3TestAdapter": { + "type": "Direct", + "requested": "[6.3.1, )", + "resolved": "6.3.1", + "contentHash": "Ft72evCCPjWhimwSda+oDDX0aStX/dty2S3clJ+tK5bMtO9u0n+521OJmsOecUmpc1a+xfhS6kUprc+Gve/wcA==", + "dependencies": { + "Microsoft.Extensions.DependencyModel": "8.0.2", + "Microsoft.TestPlatform.AdapterUtilities": "18.10.1", + "Microsoft.Testing.Extensions.VSTestBridge": "2.4.1", + "Microsoft.Testing.Platform.MSBuild": "2.4.1" + } + }, + "StyleCop.Analyzers": { + "type": "Direct", + "requested": "[1.3.180, )", + "resolved": "1.3.180", + "contentHash": "/TDyrO3tUJOsnyTazvaX+qwwBt4aixQLNLtxmkyWQZE94IOZ9PnClHrwKUVn/NSXdXUUWrKMHTtlxUkZ1F8JWg==" + }, + "Microsoft.ApplicationInsights": { + "type": "Transitive", + "resolved": "2.23.0", + "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" + }, + "Microsoft.CodeCoverage": { + "type": "Transitive", + "resolved": "18.12.0", + "contentHash": "OhOPSaCAQhBJgXF1OrX0uK3eTkwZ1XnM44iGLZplYgKrmgKzQUdv9xtGGaE568RuQ738TlrTJ3pm9aWL5FH7iw==" + }, + "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "8.0.2", + "contentHash": "mUBDZZRgZrSyFOsJ2qJJ9fXfqd/kXJwf3AiDoqLD9m6TjY5OO/vLNOb9fb4juC0487eq4hcGN/M2Rh/CKS7QYw==" + }, + "Microsoft.Testing.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "2.4.1", + "contentHash": "C+bq5ydHrBNCDXjvFtRa1/JcAS2Wq2dpXOnzy/TFYC8qb1dDEgB1XhQayBaYE/5BKviikByHb7mth8P+qJaOJw==", + "dependencies": { + "Microsoft.ApplicationInsights": "2.23.0", + "Microsoft.Testing.Platform": "[2.4.1, 3.0.0)" + } + }, + "Microsoft.Testing.Extensions.TrxReport.Abstractions": { + "type": "Transitive", + "resolved": "2.4.1", + "contentHash": "tDxLLic2IfeChbyo8oeGZj/eBdFpPe3Dp80hUoIOefSCqqMHbsob+lX1TfFWV75PJCPouxj2zz0zzPHZxiM4nQ==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.4.1, 3.0.0)" + } + }, + "Microsoft.Testing.Extensions.VSTestBridge": { + "type": "Transitive", + "resolved": "2.4.1", + "contentHash": "O+fy8t+qse6ZexS7TzuA47Z3Ojw/4x6fIF+xGSwFypgoDAg3+bFmu1vkz8smLla0A+QRopphxfBYJBOPedDPYw==", + "dependencies": { + "Microsoft.TestPlatform.ObjectModel": "18.9.0", + "Microsoft.Testing.Extensions.Telemetry": "2.4.1", + "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.4.1", + "Microsoft.Testing.Platform": "[2.4.1, 3.0.0)" + } + }, + "Microsoft.Testing.Platform": { + "type": "Transitive", + "resolved": "2.4.1", + "contentHash": "3nW9NyhN1BnHRF994DCOOUQCqVA9pDT+gPpbuhI/xUntZnGnXO4ySovKxFlFuoT/48pnI74LK/DeKVlve1L3VQ==" + }, + "Microsoft.Testing.Platform.MSBuild": { + "type": "Transitive", + "resolved": "2.4.1", + "contentHash": "K4W2hAATe9wA1xt4oEZWmUsnQqnLD5H18NXKsm81xclf9PI4AHieb3DxJpE/2uA6Xl9DtjpLXif7/9Sn8Y2y7w==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.4.1, 3.0.0)" + } + }, + "Microsoft.TestPlatform.AdapterUtilities": { + "type": "Transitive", + "resolved": "18.10.1", + "contentHash": "EDomLQOqzKhMHLWl+WlR2TEIwduApQffQKNsFBVnkjDsiNKwRpbYZPNlYcEa0CqWW+4NL0PongzgroCvaf+4zQ==" + }, + "Microsoft.TestPlatform.ObjectModel": { + "type": "Transitive", + "resolved": "18.12.0", + "contentHash": "ilT2o4v/c1joLgsfzS4dYQ71bWAy/RsA6fBY7f5OEUpUsUhwIzoliGeXdS3yctWuy4NZyuSVlO7dPX4ed7R06A==" + }, + "Microsoft.TestPlatform.TestHost": { + "type": "Transitive", + "resolved": "18.12.0", + "contentHash": "WTT912JUqmFa2BkCeXPkMCUpbYOqsbeRfRJdhaIQROx49iokgnGPAlKvXmHWKC9nJwWrHwSQfR+k+Qn7NCxfzw==", + "dependencies": { + "Microsoft.TestPlatform.ObjectModel": "18.12.0" + } + }, + "exceldatareader": { + "type": "Project" + } + }, + "net11.0": { + "Microsoft.NET.Test.Sdk": { + "type": "Direct", + "requested": "[18.12.0, )", + "resolved": "18.12.0", + "contentHash": "MdVkskM2ZCKSlNts5DIbz9MZidX7SwcXKBoBqY4XT91b30hAwC8PkjWbdGKRak6BKAD1BQqaZnh/SD0AJGoDCQ==", + "dependencies": { + "Microsoft.CodeCoverage": "18.12.0", + "Microsoft.TestPlatform.TestHost": "18.12.0" + } + }, + "NUnit": { + "type": "Direct", + "requested": "[5.0.0, )", + "resolved": "5.0.0", + "contentHash": "tW5Juazgh4CI4pXo5c9c2J9J4i9vwZMm/FJ+gRRe0plJHLCz7Ck/raPuE5q1xWmLAUwpao4Ht1Uy1uRN3Wo5sw==" + }, + "NUnit.Analyzers": { + "type": "Direct", + "requested": "[4.15.0, )", + "resolved": "4.15.0", + "contentHash": "WbZpZI/gmrmTcb8JnP8poJBD4V6hJs2RRIQAmNxQ763t7RktZ/d6xxuU08XAd4K6SpnF0Bm02ADqL2wZ0CNIQA==" + }, + "NUnit3TestAdapter": { + "type": "Direct", + "requested": "[6.3.1, )", + "resolved": "6.3.1", + "contentHash": "Ft72evCCPjWhimwSda+oDDX0aStX/dty2S3clJ+tK5bMtO9u0n+521OJmsOecUmpc1a+xfhS6kUprc+Gve/wcA==", + "dependencies": { + "Microsoft.Extensions.DependencyModel": "8.0.2", + "Microsoft.TestPlatform.AdapterUtilities": "18.10.1", + "Microsoft.Testing.Extensions.VSTestBridge": "2.4.1", + "Microsoft.Testing.Platform.MSBuild": "2.4.1" + } + }, + "StyleCop.Analyzers": { + "type": "Direct", + "requested": "[1.3.180, )", + "resolved": "1.3.180", + "contentHash": "/TDyrO3tUJOsnyTazvaX+qwwBt4aixQLNLtxmkyWQZE94IOZ9PnClHrwKUVn/NSXdXUUWrKMHTtlxUkZ1F8JWg==" + }, + "Microsoft.ApplicationInsights": { + "type": "Transitive", + "resolved": "2.23.0", + "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" + }, + "Microsoft.CodeCoverage": { + "type": "Transitive", + "resolved": "18.12.0", + "contentHash": "OhOPSaCAQhBJgXF1OrX0uK3eTkwZ1XnM44iGLZplYgKrmgKzQUdv9xtGGaE568RuQ738TlrTJ3pm9aWL5FH7iw==" + }, + "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "8.0.2", + "contentHash": "mUBDZZRgZrSyFOsJ2qJJ9fXfqd/kXJwf3AiDoqLD9m6TjY5OO/vLNOb9fb4juC0487eq4hcGN/M2Rh/CKS7QYw==" + }, + "Microsoft.Testing.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "2.4.1", + "contentHash": "C+bq5ydHrBNCDXjvFtRa1/JcAS2Wq2dpXOnzy/TFYC8qb1dDEgB1XhQayBaYE/5BKviikByHb7mth8P+qJaOJw==", + "dependencies": { + "Microsoft.ApplicationInsights": "2.23.0", + "Microsoft.Testing.Platform": "[2.4.1, 3.0.0)" + } + }, + "Microsoft.Testing.Extensions.TrxReport.Abstractions": { + "type": "Transitive", + "resolved": "2.4.1", + "contentHash": "tDxLLic2IfeChbyo8oeGZj/eBdFpPe3Dp80hUoIOefSCqqMHbsob+lX1TfFWV75PJCPouxj2zz0zzPHZxiM4nQ==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.4.1, 3.0.0)" + } + }, + "Microsoft.Testing.Extensions.VSTestBridge": { + "type": "Transitive", + "resolved": "2.4.1", + "contentHash": "O+fy8t+qse6ZexS7TzuA47Z3Ojw/4x6fIF+xGSwFypgoDAg3+bFmu1vkz8smLla0A+QRopphxfBYJBOPedDPYw==", + "dependencies": { + "Microsoft.TestPlatform.ObjectModel": "18.9.0", + "Microsoft.Testing.Extensions.Telemetry": "2.4.1", + "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.4.1", + "Microsoft.Testing.Platform": "[2.4.1, 3.0.0)" + } + }, + "Microsoft.Testing.Platform": { + "type": "Transitive", + "resolved": "2.4.1", + "contentHash": "3nW9NyhN1BnHRF994DCOOUQCqVA9pDT+gPpbuhI/xUntZnGnXO4ySovKxFlFuoT/48pnI74LK/DeKVlve1L3VQ==" + }, + "Microsoft.Testing.Platform.MSBuild": { + "type": "Transitive", + "resolved": "2.4.1", + "contentHash": "K4W2hAATe9wA1xt4oEZWmUsnQqnLD5H18NXKsm81xclf9PI4AHieb3DxJpE/2uA6Xl9DtjpLXif7/9Sn8Y2y7w==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.4.1, 3.0.0)" + } + }, + "Microsoft.TestPlatform.AdapterUtilities": { + "type": "Transitive", + "resolved": "18.10.1", + "contentHash": "EDomLQOqzKhMHLWl+WlR2TEIwduApQffQKNsFBVnkjDsiNKwRpbYZPNlYcEa0CqWW+4NL0PongzgroCvaf+4zQ==" + }, + "Microsoft.TestPlatform.ObjectModel": { + "type": "Transitive", + "resolved": "18.12.0", + "contentHash": "ilT2o4v/c1joLgsfzS4dYQ71bWAy/RsA6fBY7f5OEUpUsUhwIzoliGeXdS3yctWuy4NZyuSVlO7dPX4ed7R06A==" + }, + "Microsoft.TestPlatform.TestHost": { + "type": "Transitive", + "resolved": "18.12.0", + "contentHash": "WTT912JUqmFa2BkCeXPkMCUpbYOqsbeRfRJdhaIQROx49iokgnGPAlKvXmHWKC9nJwWrHwSQfR+k+Qn7NCxfzw==", + "dependencies": { + "Microsoft.TestPlatform.ObjectModel": "18.12.0" + } + }, + "exceldatareader": { + "type": "Project" + } + } + } +} \ No newline at end of file diff --git a/src/ExcelDataReader.Sample/App.axaml b/src/ExcelDataReader.Sample/App.axaml new file mode 100644 index 00000000..03a46dea --- /dev/null +++ b/src/ExcelDataReader.Sample/App.axaml @@ -0,0 +1,7 @@ + + + + + diff --git a/src/ExcelDataReader.Sample/App.axaml.cs b/src/ExcelDataReader.Sample/App.axaml.cs new file mode 100644 index 00000000..16b9c8dc --- /dev/null +++ b/src/ExcelDataReader.Sample/App.axaml.cs @@ -0,0 +1,23 @@ +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; + +namespace ExcelDataReader.Sample; + +internal sealed class App : Application +{ + public override void Initialize() + { + AvaloniaXamlLoader.Load(this); + } + + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + desktop.MainWindow = new MainWindow(); + } + + base.OnFrameworkInitializationCompleted(); + } +} diff --git a/src/ExcelDataReader.Sample/ExcelDataReader.Sample.csproj b/src/ExcelDataReader.Sample/ExcelDataReader.Sample.csproj index d20df78e..ec5d0232 100644 --- a/src/ExcelDataReader.Sample/ExcelDataReader.Sample.csproj +++ b/src/ExcelDataReader.Sample/ExcelDataReader.Sample.csproj @@ -1,31 +1,21 @@ - + - net462;net8.0-windows - TestApp WinExe - TestApp - true + net10.0 + ExcelDataReader.Sample + enable - - - - - - - - - - - + + + - - Form - + + diff --git a/src/ExcelDataReader.Sample/Form1.Designer.cs b/src/ExcelDataReader.Sample/Form1.Designer.cs deleted file mode 100644 index 7d717f16..00000000 --- a/src/ExcelDataReader.Sample/Form1.Designer.cs +++ /dev/null @@ -1,210 +0,0 @@ -// -using System.Data; -using System.Diagnostics; - -namespace ExcelDataReader.Sample; - -public partial class Form1 -{ - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); - this.button1 = new System.Windows.Forms.Button(); - this.textBox1 = new System.Windows.Forms.TextBox(); - this.button2 = new System.Windows.Forms.Button(); - this.dataSet1 = new System.Data.DataSet(); - this.dataGridView1 = new System.Windows.Forms.DataGridView(); - this.sheetCombo = new System.Windows.Forms.ComboBox(); - this.Sheet = new System.Windows.Forms.Label(); - this.firstRowNamesCheckBox = new System.Windows.Forms.CheckBox(); - this.statusStrip1 = new System.Windows.Forms.StatusStrip(); - this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); - this.label1 = new System.Windows.Forms.Label(); - ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); - this.statusStrip1.SuspendLayout(); - this.SuspendLayout(); - // - // openFileDialog1 - // - this.openFileDialog1.FileName = "openFileDialog1"; - this.openFileDialog1.Filter = "Supported files|*.xls;*.xlsx;*.xlsb;*.csv|xls|*.xls|xlsx|*.xlsx|xlsb|*.xlsb|csv|*" + -".csv|All|*.*"; - // - // button1 - // - this.button1.Location = new System.Drawing.Point(345, 5); - this.button1.Margin = new System.Windows.Forms.Padding(2); - this.button1.Name = "button1"; - this.button1.Size = new System.Drawing.Size(70, 21); - this.button1.TabIndex = 0; - this.button1.Text = "Select file"; - this.button1.UseVisualStyleBackColor = true; - this.button1.Click += new System.EventHandler(this.Button1Click); - // - // textBox1 - // - this.textBox1.Location = new System.Drawing.Point(46, 6); - this.textBox1.Margin = new System.Windows.Forms.Padding(2); - this.textBox1.Name = "textBox1"; - this.textBox1.Size = new System.Drawing.Size(295, 20); - this.textBox1.TabIndex = 1; - // - // button2 - // - this.button2.Location = new System.Drawing.Point(11, 51); - this.button2.Margin = new System.Windows.Forms.Padding(2); - this.button2.Name = "button2"; - this.button2.Size = new System.Drawing.Size(73, 29); - this.button2.TabIndex = 2; - this.button2.Text = "Process"; - this.button2.UseVisualStyleBackColor = true; - this.button2.Click += new System.EventHandler(this.Button2Click); - // - // dataSet1 - // - this.dataSet1.DataSetName = "NewDataSet"; - // - // dataGridView1 - // - this.dataGridView1.AllowUserToAddRows = false; - this.dataGridView1.AllowUserToDeleteRows = false; - this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.dataGridView1.Location = new System.Drawing.Point(11, 114); - this.dataGridView1.Margin = new System.Windows.Forms.Padding(2); - this.dataGridView1.Name = "dataGridView1"; - this.dataGridView1.ReadOnly = true; - this.dataGridView1.RowTemplate.Height = 24; - this.dataGridView1.Size = new System.Drawing.Size(865, 426); - this.dataGridView1.TabIndex = 3; - // - // sheetCombo - // - this.sheetCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - this.sheetCombo.FormattingEnabled = true; - this.sheetCombo.Location = new System.Drawing.Point(88, 89); - this.sheetCombo.Margin = new System.Windows.Forms.Padding(2); - this.sheetCombo.Name = "sheetCombo"; - this.sheetCombo.Size = new System.Drawing.Size(253, 21); - this.sheetCombo.TabIndex = 4; - this.sheetCombo.SelectedIndexChanged += new System.EventHandler(this.SheetComboSelectedIndexChanged); - // - // Sheet - // - this.Sheet.AutoSize = true; - this.Sheet.Location = new System.Drawing.Point(12, 92); - this.Sheet.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); - this.Sheet.Name = "Sheet"; - this.Sheet.Size = new System.Drawing.Size(72, 13); - this.Sheet.TabIndex = 5; - this.Sheet.Text = "Choose sheet"; - // - // firstRowNamesCheckBox - // - this.firstRowNamesCheckBox.AutoSize = true; - this.firstRowNamesCheckBox.Checked = true; - this.firstRowNamesCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; - this.firstRowNamesCheckBox.Location = new System.Drawing.Point(15, 30); - this.firstRowNamesCheckBox.Margin = new System.Windows.Forms.Padding(2); - this.firstRowNamesCheckBox.Name = "firstRowNamesCheckBox"; - this.firstRowNamesCheckBox.Size = new System.Drawing.Size(176, 17); - this.firstRowNamesCheckBox.TabIndex = 6; - this.firstRowNamesCheckBox.Text = "first row contains column names"; - this.firstRowNamesCheckBox.UseVisualStyleBackColor = true; - // - // statusStrip1 - // - this.statusStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); - this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.toolStripStatusLabel1}); - this.statusStrip1.Location = new System.Drawing.Point(0, 552); - this.statusStrip1.Name = "statusStrip1"; - this.statusStrip1.Padding = new System.Windows.Forms.Padding(1, 0, 10, 0); - this.statusStrip1.Size = new System.Drawing.Size(887, 22); - this.statusStrip1.TabIndex = 7; - this.statusStrip1.Text = "statusStrip1"; - // - // toolStripStatusLabel1 - // - this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; - this.toolStripStatusLabel1.Size = new System.Drawing.Size(0, 17); - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(12, 9); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(29, 13); - this.label1.TabIndex = 8; - this.label1.Text = "Path"; - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(887, 574); - this.Controls.Add(this.label1); - this.Controls.Add(this.statusStrip1); - this.Controls.Add(this.firstRowNamesCheckBox); - this.Controls.Add(this.Sheet); - this.Controls.Add(this.sheetCombo); - this.Controls.Add(this.dataGridView1); - this.Controls.Add(this.button2); - this.Controls.Add(this.textBox1); - this.Controls.Add(this.button1); - this.Margin = new System.Windows.Forms.Padding(2); - this.Name = "Form1"; - this.Text = "Form1"; - ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); - this.statusStrip1.ResumeLayout(false); - this.statusStrip1.PerformLayout(); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.OpenFileDialog openFileDialog1; - private System.Windows.Forms.Button button1; - private System.Windows.Forms.TextBox textBox1; - private System.Windows.Forms.Button button2; - private System.Data.DataSet dataSet1; - private System.Windows.Forms.DataGridView dataGridView1; - private System.Windows.Forms.ComboBox sheetCombo; - private System.Windows.Forms.Label Sheet; - private System.Windows.Forms.CheckBox firstRowNamesCheckBox; - private StatusStrip statusStrip1; - private ToolStripStatusLabel toolStripStatusLabel1; - private Label label1; - private DataSet ds; -} diff --git a/src/ExcelDataReader.Sample/Form1.cs b/src/ExcelDataReader.Sample/Form1.cs deleted file mode 100644 index a4205ad4..00000000 --- a/src/ExcelDataReader.Sample/Form1.cs +++ /dev/null @@ -1,99 +0,0 @@ -// -using System.Data; -using System.Diagnostics; - -namespace ExcelDataReader.Sample; - -public partial class Form1 : Form -{ - public Form1() - { - InitializeComponent(); - } - - /* - public static void GetValues(DataSet dataset, string sheetName) - { - foreach (DataRow row in dataset.Tables[sheetName].Rows) - { - foreach (var value in row.ItemArray) - { - Console.WriteLine("{0}, {1}", value, value.GetType()); - } - } - } - */ - - private static IList GetTablenames(DataTableCollection tables) - { - var tableList = new List(tables.Count); - foreach (var table in tables) - { - tableList.Add(table.ToString()); - } - - return tableList; - } - - private void Button1Click(object sender, EventArgs e) - { - var result = openFileDialog1.ShowDialog(); - if (result == DialogResult.OK) - { - textBox1.Text = openFileDialog1.FileName; - } - } - - private void Button2Click(object sender, EventArgs e) - { - try - { - using var stream = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - - var sw = new Stopwatch(); - sw.Start(); - - using IExcelDataReader reader = string.Equals(Path.GetExtension(textBox1.Text), ".csv", StringComparison.OrdinalIgnoreCase) ? - ExcelReaderFactory.CreateCsvReader(stream) : ExcelReaderFactory.CreateReader(stream); - - var openTiming = sw.ElapsedMilliseconds; - // reader.IsFirstRowAsColumnNames = firstRowNamesCheckBox.Checked; - ds = reader.AsDataSet(new ExcelDataSetConfiguration() - { - UseColumnDataType = false, - ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration() - { - UseHeaderRow = firstRowNamesCheckBox.Checked - } - }); - - toolStripStatusLabel1.Text = "Elapsed: " + sw.ElapsedMilliseconds.ToString() + " ms (" + openTiming.ToString() + " ms to open)"; - - var tablenames = GetTablenames(ds.Tables); - sheetCombo.DataSource = tablenames; - - if (tablenames.Count > 0) - sheetCombo.SelectedIndex = 0; - } - catch (Exception ex) - { - MessageBox.Show(ex.ToString(), ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - private void SelectTable() - { - var tablename = sheetCombo.SelectedItem.ToString(); - - dataGridView1.AutoGenerateColumns = true; - dataGridView1.DataSource = ds; // dataset - dataGridView1.DataMember = tablename; - - // GetValues(ds, tablename); - } - - private void SheetComboSelectedIndexChanged(object sender, EventArgs e) - { - SelectTable(); - } -} diff --git a/src/ExcelDataReader.Sample/Form1.resx b/src/ExcelDataReader.Sample/Form1.resx deleted file mode 100644 index f38a18d2..00000000 --- a/src/ExcelDataReader.Sample/Form1.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - 157, 17 - - - 256, 17 - - \ No newline at end of file diff --git a/src/ExcelDataReader.Sample/MainWindow.axaml b/src/ExcelDataReader.Sample/MainWindow.axaml new file mode 100644 index 00000000..7fc20dbc --- /dev/null +++ b/src/ExcelDataReader.Sample/MainWindow.axaml @@ -0,0 +1,67 @@ + + + + + +