-
Notifications
You must be signed in to change notification settings - Fork 415
Prefix post-2007 function names with _xlfn so formulas work in Excel #1742
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
Mike-Crowley
wants to merge
4
commits into
dfinke:master
Choose a base branch
from
Mike-Crowley:fix-1728-xlfn-prefix
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 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
ac32678
Prefix post-2007 function names with _xlfn so formulas work in Excel
Mike-Crowley 1135710
Address review findings on the _xlfn prefix table
Mike-Crowley 618a81f
Commit the script which generates the _xlfn function table
Mike-Crowley 123a914
Register the _xlfn._xlws alias too, as Copilot review suggested
Mike-Crowley 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| # Functions added to Excel after the 2007 file format was defined are stored inside the xlsx file | ||
| # with an "_xlfn." prefix (SORT and FILTER use "_xlfn._xlws."). Excel adds the prefix invisibly when | ||
| # a formula is typed in, but when a formula is written straight into the file - as EPPlus does - the | ||
| # prefix must already be present: without it Excel treats the name as an unknown defined name and the | ||
| # cell shows #NAME? until it is manually re-entered (see issue #1728 and | ||
| # https://support.microsoft.com/en-us/office/issue-an-xlfn-prefix-is-displayed-in-front-of-a-formula-882f1ef7-68fb-4fcd-8d54-9fbb77fd5025 ). | ||
| # This table maps each affected function to its prefix. It was generated by entering candidate | ||
| # functions into Excel (Microsoft 365) via COM, reading back what Excel stored in the worksheet XML, | ||
| # and cross-checking against the future-function lists other xlsx writers (XlsxWriter, PhpSpreadsheet) | ||
| # use. NETWORKDAYS.INTL, WORKDAY.INTL and ISO.CEILING are absent deliberately - Excel stores them | ||
| # unprefixed, although PhpSpreadsheet believes otherwise. The script which regenerates this table from | ||
| # the installed Excel - and verifies the table against it - is __tests__\Get-XlFnFunctionList.ps1, | ||
| # with its latest output in __tests__\XlFnFunctionList.txt. | ||
| $script:XlFnFunctionPrefix = @{} | ||
| foreach ($functionName in @( | ||
| #Added in Excel 2010 | ||
| 'AGGREGATE', 'BETA.DIST', 'BETA.INV', 'BINOM.DIST', 'BINOM.INV', 'CEILING.PRECISE', 'CHISQ.DIST', | ||
| 'CHISQ.DIST.RT', 'CHISQ.INV', 'CHISQ.INV.RT', 'CHISQ.TEST', 'CONFIDENCE.NORM', 'CONFIDENCE.T', | ||
| 'COVARIANCE.P', 'COVARIANCE.S', 'ERF.PRECISE', 'ERFC.PRECISE', 'EXPON.DIST', 'F.DIST', 'F.DIST.RT', | ||
| 'F.INV', 'F.INV.RT', 'F.TEST', 'FLOOR.PRECISE', 'GAMMA.DIST', 'GAMMA.INV', 'GAMMALN.PRECISE', | ||
| 'HYPGEOM.DIST', 'LOGNORM.DIST', 'LOGNORM.INV', 'MODE.MULT', 'MODE.SNGL', 'NEGBINOM.DIST', 'NORM.DIST', | ||
| 'NORM.INV', 'NORM.S.DIST', 'NORM.S.INV', 'PERCENTILE.EXC', 'PERCENTILE.INC', 'PERCENTRANK.EXC', | ||
| 'PERCENTRANK.INC', 'POISSON.DIST', 'QUARTILE.EXC', 'QUARTILE.INC', 'RANK.AVG', 'RANK.EQ', 'STDEV.P', | ||
| 'STDEV.S', 'T.DIST', 'T.DIST.2T', 'T.DIST.RT', 'T.INV', 'T.INV.2T', 'T.TEST', 'VAR.P', 'VAR.S', | ||
| 'WEIBULL.DIST', 'Z.TEST', | ||
| #Added in Excel 2013 | ||
| 'ACOT', 'ACOTH', 'ARABIC', 'BASE', 'BINOM.DIST.RANGE', 'BITAND', 'BITLSHIFT', 'BITOR', 'BITRSHIFT', | ||
| 'BITXOR', 'CEILING.MATH', 'COMBINA', 'COT', 'COTH', 'CSC', 'CSCH', 'DAYS', 'DECIMAL', 'ENCODEURL', | ||
| 'FILTERXML', 'FLOOR.MATH', 'FORMULATEXT', 'GAMMA', 'GAUSS', 'IFNA', 'IMCOSH', 'IMCOT', 'IMCSC', | ||
| 'IMCSCH', 'IMSEC', 'IMSECH', 'IMSINH', 'IMTAN', 'ISFORMULA', 'ISOWEEKNUM', 'MUNIT', 'NUMBERVALUE', | ||
| 'PDURATION', 'PERMUTATIONA', 'PHI', 'RRI', 'SEC', 'SECH', 'SHEET', 'SHEETS', 'SKEW.P', 'UNICHAR', | ||
| 'UNICODE', 'WEBSERVICE', 'XOR', | ||
| #Added in Excel 2016 | ||
| 'FORECAST.ETS', 'FORECAST.ETS.CONFINT', 'FORECAST.ETS.SEASONALITY', 'FORECAST.ETS.STAT', | ||
| 'FORECAST.LINEAR', | ||
| #Added in Excel 2019 | ||
| 'CONCAT', 'IFS', 'MAXIFS', 'MINIFS', 'SWITCH', 'TEXTJOIN', | ||
| #Added in Excel 2021 / Microsoft 365 | ||
| 'ARRAYTOTEXT', 'BYCOL', 'BYROW', 'CHOOSECOLS', 'CHOOSEROWS', 'DROP', 'EXPAND', 'GROUPBY', 'HSTACK', | ||
| 'IMAGE', 'ISOMITTED', 'LAMBDA', 'LET', 'MAKEARRAY', 'MAP', 'PERCENTOF', 'PIVOTBY', 'RANDARRAY', | ||
| 'REDUCE', 'REGEXEXTRACT', 'REGEXREPLACE', 'REGEXTEST', 'SCAN', 'SEQUENCE', 'SORTBY', 'STOCKHISTORY', | ||
| 'TAKE', 'TEXTAFTER', 'TEXTBEFORE', 'TEXTSPLIT', 'TOCOL', 'TOROW', 'TRIMRANGE', 'UNIQUE', | ||
| 'VALUETOTEXT', 'VSTACK', 'WRAPCOLS', 'WRAPROWS', 'XLOOKUP', 'XMATCH' | ||
| )) { $script:XlFnFunctionPrefix[$functionName] = '_xlfn.' } | ||
| foreach ($functionName in @('FILTER', 'SORT')) { $script:XlFnFunctionPrefix[$functionName] = '_xlfn._xlws.' } | ||
|
|
||
| #A function name counts as a match only when it is not part of a longer or already-prefixed name | ||
| #(no word character or "." before it) and a "(" follows it. Names are sorted longest first so that | ||
| #e.g. CHISQ.DIST.RT is preferred over CHISQ.DIST. | ||
| #The Compiled option is deliberately not used: it makes construction ~20x slower (paid at module load) | ||
| #and measures no faster on these patterns - .NET's interpreted engine handles the alternation well. | ||
| $script:XlFnRegexOptions = [System.Text.RegularExpressions.RegexOptions]'IgnoreCase, CultureInvariant' | ||
| $script:XlFnEscapedNames = ($script:XlFnFunctionPrefix.Keys | Sort-Object -Property Length -Descending | | ||
| ForEach-Object { [regex]::Escape($_) }) -join '|' | ||
| $script:XlFnNameTestRegex = [regex]::new("(?<![\w.])(?:$script:XlFnEscapedNames)(?=\s*\()", $script:XlFnRegexOptions) | ||
| #Matches the constructs a function name must not be rewritten inside: "string literals" and 'quoted | ||
| #sheet names' (a doubled quote is an escape) and [structured references] (where ' escapes the next | ||
| #character; nested forms like [[#This Row],[Name]] are covered because every name lives in an | ||
| #innermost bracket pair). | ||
| $script:XlFnSkipRegex = [regex]::new('"(?:[^"]|"")*"|''(?:[^'']|'''')*''|\[(?:[^\[\]'']|''.)*\]', $script:XlFnRegexOptions) | ||
| #Two replacement patterns, one per prefix, both run after the skip sections are cut out. The two name | ||
| #sets are disjoint and the "(?=\s*\()" lookahead keeps e.g. SORTBY( from matching SORT, so the passes | ||
| #cannot interfere with each other. | ||
| $script:XlFnPlainNames = ($script:XlFnFunctionPrefix.GetEnumerator() | Where-Object Value -eq '_xlfn.' | | ||
| Sort-Object { $_.Key.Length } -Descending | ForEach-Object { [regex]::Escape($_.Key) }) -join '|' | ||
| $script:XlFnNameRegex = [regex]::new("(?<![\w.])(?:$script:XlFnPlainNames)(?=\s*\()", $script:XlFnRegexOptions) | ||
| $script:XlFnXlwsNameRegex = [regex]::new('(?<![\w.])(?:FILTER|SORT)(?=\s*\()', $script:XlFnRegexOptions) | ||
|
|
||
| function Expand-XlFnFormula { | ||
| <# | ||
| .SYNOPSIS | ||
| Inserts the "_xlfn." prefixes Excel needs in front of post-2007 function names in a formula. | ||
| .DESCRIPTION | ||
| Given a formula string (without its leading "="), returns the formula with function names | ||
| like IFS or CONCAT rewritten as _xlfn.IFS / _xlfn.CONCAT so Excel recognizes them when the | ||
| file is opened; Excel displays and calculates the formula as if the prefix were not there. | ||
| "String literals", 'quoted sheet names' and [structured references] are left untouched, as | ||
| are names that already carry a prefix. Setting $env:NoXlFn disables the transformation. | ||
| #> | ||
| param( | ||
| [AllowEmptyString()][AllowNull()][String]$Formula | ||
| ) | ||
| if (-not $Formula -or $env:NoXlFn) { return $Formula } | ||
| #Most formulas contain no affected function: test cheaply before rewriting. A false positive here | ||
| #(the name only occurs inside a string or bracket) costs a rewrite pass which changes nothing. | ||
| if (-not $script:XlFnNameTestRegex.IsMatch($Formula)) { return $Formula } | ||
| $skips = $script:XlFnSkipRegex.Matches($Formula) | ||
| if ($skips.Count -eq 0) { | ||
| return $script:XlFnXlwsNameRegex.Replace($script:XlFnNameRegex.Replace($Formula, '_xlfn.$&'), '_xlfn._xlws.$&') | ||
| } | ||
| #Rewrite the stretches between the protected sections, and copy the protected sections through. | ||
| $builder = [System.Text.StringBuilder]::new($Formula.Length + 16) | ||
| $position = 0 | ||
| foreach ($skip in $skips) { | ||
| if ($skip.Index -gt $position) { | ||
| $segment = $Formula.Substring($position, $skip.Index - $position) | ||
| [void]$builder.Append($script:XlFnXlwsNameRegex.Replace($script:XlFnNameRegex.Replace($segment, '_xlfn.$&'), '_xlfn._xlws.$&')) | ||
| } | ||
| [void]$builder.Append($skip.Value) | ||
| $position = $skip.Index + $skip.Length | ||
| } | ||
| if ($position -lt $Formula.Length) { | ||
| $segment = $Formula.Substring($position) | ||
| [void]$builder.Append($script:XlFnXlwsNameRegex.Replace($script:XlFnNameRegex.Replace($segment, '_xlfn.$&'), '_xlfn._xlws.$&')) | ||
| } | ||
| return $builder.ToString() | ||
| } | ||
|
|
||
| function Register-XlFnFunction { | ||
| <# | ||
| .SYNOPSIS | ||
| Teaches EPPlus's calculation engine the "_xlfn."-prefixed aliases of the functions it implements. | ||
| .DESCRIPTION | ||
| The calculation engine looks functions up by the name stored in the formula, so _xlfn.IFNA would | ||
| not be found even though IFNA is implemented. Registering each implemented function again under | ||
| its _xlfn. name lets Calculate() work on formulas written by Expand-XlFnFormula. Functions the | ||
| engine does not implement still produce #NAME? when calculated, exactly as they did before. | ||
| #> | ||
| param( | ||
| [Parameter(Mandatory = $true)][OfficeOpenXml.ExcelWorkbook]$Workbook | ||
| ) | ||
| $parserManager = $Workbook.FormulaParserManager | ||
| foreach ($implemented in @($parserManager.GetImplementedFunctions())) { | ||
| if ($implemented.Key -notlike '_xlfn.*') { | ||
| $parserManager.AddOrReplaceFunction("_xlfn.$($implemented.Key)", $implemented.Value) | ||
| } | ||
| } | ||
| } | ||
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
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.