antonmihaylov / OpenXmlTemplates

Word .docx templating system that is designer (no scripting tags) and server-friendly (no word installation required)
GNU Lesser General Public License v3.0
92 stars 25 forks source link

Numeric formatting #20

Closed dgwaldo closed 2 years ago

dgwaldo commented 3 years ago

I've added numeric formatting, would be nice to get it back to this repo. Would you be interested in a PR for that?

https://github.com/dgwaldo/OpenXmlTemplates?organization=dgwaldo&organization=dgwaldo

Also, would be nice to get an update to the NuGet package.

antonmihaylov commented 3 years ago

PR would be appreciated

Update about the package bug I'll push your changes to nuget after PR

How does the numeric format work btw

dgwaldo commented 3 years ago

Root of the logic is here in VariableSource.cs

   /// <summary>
        /// Parses the variable identifier and returns the corresponding value from the currently loaded data.
        /// If no data is loaded null is returned.
        /// </summary>
        /// <param name="variabeIdentifier">The variable identifier</param>
        /// <param name="allowNull">If this is false and the value is null an IncorrectIdentifierException exception is thrown</param>
        /// <returns>The found variable value or null if there is no data loaded or the variable is not found (in case throwIfNotFound is false)</returns>
        /// <exception cref="IncorrectVariableTypeException"></exception>
        public virtual object GetVariable(string variabeIdentifier)
        {
            var identifierSplittedByDot = variabeIdentifier.Split('.');

            if (Data == null || Data.Count == 0) return null;

            var lastNestedStructure = Data;
            IList lastList = null;
            object lastValue = null;

            var formatStr = GetStringFormatter(variabeIdentifier);
            foreach (var id in identifierSplittedByDot)
            {
                if (ParseVariableIdentifier(variabeIdentifier, id,
                    ref lastList, ref lastNestedStructure, ref lastValue, out var variableFromDictionary))
                    return variableFromDictionary;
            }

            return string.IsNullOrEmpty(formatStr) ? lastValue : (lastValue == null ? "" : decimal.Parse(lastValue.ToString()).ToString(formatStr));
        }
dgwaldo commented 2 years ago

Sorry about the formatting in the PR, VS has been ignoring my editor config. Might be easier to just pick out the new code if the formatting is an issue.

antonmihaylov commented 2 years ago

No problem. Sorry for the big delay, I'm too busy at work recently and forgot to merge and publish it. Published to Nuget in https://github.com/antonmihaylov/OpenXmlTemplates/releases/tag/v2.0.4

Thanks again!