Repository navigation
Add QueryCells to read cell formulas, font colors and number formats #1020
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
virzak
wants to merge
8
commits into
mini-software:master
Choose a base branch
from
virzak:feature/read-cell-formula-font
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
7182657
Add QueryCells to read cell formulas and font colors
virzak 88a3636
Report cell number formats from QueryCells
virzak 643215a
Document QueryCells in README_V2
virzak 08a6fd6
Reject out-of-range cell references in QueryCells
virzak 6507859
Build ExcelCell.Reference on demand
virzak 272a57c
Benchmark QueryCells
virzak ea3a166
Make ExcelCell a readonly struct
virzak 3544f39
Minor changes
michelebastione File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| namespace MiniExcelLib.OpenXml.Models; | ||
|
|
||
| /// <summary> | ||
| /// A worksheet cell together with the metadata that row queries leave out. | ||
| /// </summary> | ||
| public readonly struct ExcelCell | ||
| { | ||
| internal ExcelCell(int rowIndex, int columnIndex, object? value, bool hasFormula, string? formula, ExcelColor? fontColor, string? numberFormat) | ||
| { | ||
| RowIndex = rowIndex; | ||
| ColumnIndex = columnIndex; | ||
| Value = value; | ||
| HasFormula = hasFormula; | ||
| Formula = formula; | ||
| FontColor = fontColor; | ||
| NumberFormat = numberFormat; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// The A1-style reference of the cell, e.g. "B3". | ||
| /// </summary> | ||
| // Built on demand: most callers only need the indices, and a string per cell adds up on large sheets | ||
| public string Reference => CellReferenceConverter.GetCellFromCoordinates(ColumnIndex, RowIndex); | ||
|
|
||
| /// <summary> | ||
| /// The 1-based row number of the cell. | ||
| /// </summary> | ||
| public int RowIndex { get; } | ||
|
|
||
| /// <summary> | ||
| /// The 1-based column number of the cell. | ||
| /// </summary> | ||
| public int ColumnIndex { get; } | ||
|
|
||
| /// <summary> | ||
| /// The cell value, converted the same way as in row queries. For formula cells this is the result cached by the application that last saved the file. | ||
| /// </summary> | ||
| public object? Value { get; } | ||
|
|
||
| /// <summary> | ||
| /// True when the value of the cell is computed by a formula. | ||
| /// </summary> | ||
| public bool HasFormula { get; } | ||
|
|
||
| /// <summary> | ||
| /// The formula text as stored in the file, without the leading '='. | ||
| /// Cells that only share the formula of another cell report <see cref="HasFormula"/> as true and this property as <see langword="null"/>. | ||
| /// </summary> | ||
| public string? Formula { get; } | ||
|
|
||
| /// <summary> | ||
| /// The font color applied to the cell, or <see langword="null"/> when its font declares no color. | ||
| /// </summary> | ||
| public ExcelColor? FontColor { get; } | ||
|
|
||
| /// <summary> | ||
| /// The number format code of the cell, e.g. "0.0%", or <see langword="null"/> for the General format. | ||
| /// </summary> | ||
| public string? NumberFormat { get; } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// A color as declared in the workbook styles. Exactly one of <see cref="Auto"/>, <see cref="Rgb"/>, <see cref="Theme"/> or <see cref="Indexed"/> is normally set. | ||
| /// </summary> | ||
| public class ExcelColor | ||
| { | ||
| internal ExcelColor(bool auto, string? rgb, int? theme, int? indexed, double tint) | ||
| { | ||
| Auto = auto; | ||
| Rgb = rgb; | ||
| Theme = theme; | ||
| Indexed = indexed; | ||
| Tint = tint; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// True when the color is the automatic system color. | ||
| /// </summary> | ||
| public bool Auto { get; } | ||
|
|
||
| /// <summary> | ||
| /// The ARGB hex value, e.g. "FF000000". | ||
| /// </summary> | ||
| public string? Rgb { get; } | ||
|
|
||
| /// <summary> | ||
| /// The zero-based index into the workbook theme colors (0 = Light 1, 1 = Dark 1, 2 = Light 2, 3 = Dark 2, 4-9 = Accent 1-6). | ||
| /// </summary> | ||
| public int? Theme { get; } | ||
|
|
||
| /// <summary> | ||
| /// The index into the legacy indexed color palette. | ||
| /// </summary> | ||
| public int? Indexed { get; } | ||
|
|
||
| /// <summary> | ||
| /// The lightening (positive) or darkening (negative) applied to the color, from -1 to 1. | ||
| /// </summary> | ||
| public double Tint { get; } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| using MiniExcelLib.OpenXml.Styles; | ||
| using XmlReaderHelper = MiniExcelLib.OpenXml.Utils.XmlReaderHelper; | ||
|
|
||
| namespace MiniExcelLib.OpenXml.Reader; | ||
|
|
||
| internal partial class OpenXmlReader | ||
| { | ||
| [CreateSyncVersion] | ||
| internal async IAsyncEnumerable<ExcelCell> QueryCellsAsync(string? sheetName, [EnumeratorCancellation] CancellationToken cancellationToken = default) | ||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| var sheetEntry = GetSheetEntry(sheetName); | ||
| var sheetStream = await sheetEntry.OpenAsync(cancellationToken).ConfigureAwait(false); | ||
| await using var disposableSheetStream = sheetStream.ConfigureAwait(false); | ||
|
|
||
| using var reader = XmlReader.Create(sheetStream, XmlReaderHelper.GetXmlReaderSettings()); | ||
|
|
||
| if (!reader.IsStartElement("worksheet", Ns)) | ||
| yield break; | ||
| if (!await reader.ReadFirstContentAsync(cancellationToken).ConfigureAwait(false)) | ||
| yield break; | ||
|
|
||
| while (!reader.EOF) | ||
| { | ||
| if (!reader.IsStartElement("sheetData", Ns)) | ||
| { | ||
| if (!await reader.SkipContentAsync(cancellationToken).ConfigureAwait(false)) | ||
| break; | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| if (!await reader.ReadFirstContentAsync(cancellationToken).ConfigureAwait(false)) | ||
| yield break; | ||
|
|
||
| var rowNumber = 0; | ||
| while (!reader.EOF) | ||
| { | ||
| if (reader.IsStartElement("row", Ns)) | ||
| { | ||
| if (reader.GetAttribute("r") is { } rowAttribute) | ||
| { | ||
| if (!int.TryParse(rowAttribute, NumberStyles.None, CultureInfo.InvariantCulture, out rowNumber) || | ||
| rowNumber is < 1 or > CellReferenceConverter.MaxRowNumber) | ||
| { | ||
| throw new InvalidDataException($"Row index '{rowAttribute}' is outside Excel's valid range."); | ||
| } | ||
| } | ||
| else if (++rowNumber > CellReferenceConverter.MaxRowNumber) | ||
| { | ||
| throw new InvalidDataException("The worksheet contains more rows than Excel supports."); | ||
| } | ||
|
|
||
| if (!await reader.ReadFirstContentAsync(cancellationToken).ConfigureAwait(false)) | ||
| continue; | ||
|
|
||
| var columnNumber = 0; | ||
| while (!reader.EOF) | ||
| { | ||
| if (reader.IsStartElement("c", Ns)) | ||
| { | ||
| var cell = await ReadCellAsync(reader, rowNumber, columnNumber + 1, cancellationToken).ConfigureAwait(false); | ||
| columnNumber = cell.ColumnIndex; | ||
| yield return cell; | ||
| } | ||
| else if (!await reader.SkipContentAsync(cancellationToken).ConfigureAwait(false)) | ||
| { | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| else if (!await reader.SkipContentAsync(cancellationToken).ConfigureAwait(false)) | ||
| { | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| yield break; | ||
| } | ||
| } | ||
|
|
||
| [CreateSyncVersion] | ||
| private async Task<ExcelCell> ReadCellAsync(XmlReader reader, int rowNumber, int nextColumnNumber, CancellationToken cancellationToken) | ||
| { | ||
| var aR = reader.GetAttribute("r"); | ||
| var aT = reader.GetAttribute("t"); | ||
| var aS = reader.GetAttribute("s"); | ||
|
|
||
| var columnNumber = nextColumnNumber; | ||
| if (CellReferenceConverter.TryParseCellReference(aR, out var referenceColumn, out _)) | ||
| { | ||
| columnNumber = referenceColumn; | ||
| } | ||
| else if (!string.IsNullOrEmpty(aR) && referenceColumn > CellReferenceConverter.MaxColumnNumber) | ||
| { | ||
| throw new InvalidDataException($"Cell reference '{aR}' is invalid."); | ||
| } | ||
| else if (columnNumber > CellReferenceConverter.MaxColumnNumber) | ||
| { | ||
| throw new InvalidDataException("The worksheet contains more columns than Excel supports."); | ||
| } | ||
|
|
||
| object? value = null; | ||
| var hasFormula = false; | ||
| string? formula = null; | ||
|
|
||
| if (await reader.ReadFirstContentAsync(cancellationToken).ConfigureAwait(false)) | ||
| { | ||
| while (!reader.EOF) | ||
| { | ||
| if (reader.IsStartElement("f", Ns)) | ||
| { | ||
| hasFormula = true; | ||
| var formulaText = await reader.ReadElementContentAsStringAsync() | ||
| #if NET | ||
| .WaitAsync(cancellationToken) | ||
| #endif | ||
| .ConfigureAwait(false); | ||
|
|
||
| formula = string.IsNullOrEmpty(formulaText) ? null : formulaText; | ||
| } | ||
| else if (reader.IsStartElement("v", Ns)) | ||
| { | ||
| var rawValue = await reader.ReadElementContentAsStringAsync() | ||
| #if NET | ||
| .WaitAsync(cancellationToken) | ||
| #endif | ||
| .ConfigureAwait(false); | ||
|
|
||
| if (!string.IsNullOrEmpty(rawValue)) | ||
| ConvertCellValue(rawValue, aT, -1, out value); | ||
| } | ||
| else if (reader.IsStartElement("is", Ns)) | ||
| { | ||
| var rawValue = await reader.ReadStringItemAsync(cancellationToken).ConfigureAwait(false); | ||
| if (!string.IsNullOrEmpty(rawValue)) | ||
| ConvertCellValue(rawValue, aT, -1, out value); | ||
| } | ||
| else if (!await reader.SkipContentAsync(cancellationToken).ConfigureAwait(false)) | ||
| { | ||
| break; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // A cell without an s attribute uses the first cell format, so its font is the workbook default font | ||
| var hasStyleIndex = int.TryParse(aS, NumberStyles.Any, CultureInfo.InvariantCulture, out var xfIndex); | ||
| ExcelColor? fontColor = null; | ||
| string? numberFormat = null; | ||
| if (hasStyleIndex || Archive.GetEntry(ExcelFileNames.Styles) is not null) | ||
| { | ||
| _style ??= await OpenXmlStyles.CreateAsync(Archive, cancellationToken).ConfigureAwait(false); | ||
| if (hasStyleIndex) | ||
| value = _style.ConvertValueByStyleFormat(xfIndex, value); | ||
|
|
||
| fontColor = _style.GetFontColor(xfIndex); | ||
| if (_style.GetStyleFormat(xfIndex)?.FormatCode is { } formatCode and not "General") | ||
| numberFormat = formatCode; | ||
| } | ||
|
|
||
| return new ExcelCell(rowNumber, columnNumber, value, hasFormula, formula, fontColor, numberFormat); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.