[NWD] Remove more dead code in EPPlus. Change-Id: If3334f3fa0a5ae56e6c328cb4d34c4ecf1c5315d Reviewed-on: https://gnocchi-internal-review.git.corp.google.com/c/third_party/epplus/+/207760 Reviewed-by: Hughes Hilton <hugheshilton@google.com>
diff --git a/EPPlus/CellStore.cs b/EPPlus/CellStore.cs index 71aece7..a00f890 100644 --- a/EPPlus/CellStore.cs +++ b/EPPlus/CellStore.cs
@@ -1184,25 +1184,9 @@ page.Index--; page.Offset += _pageSize; } - //else if (page.Rows[0].Index >= PageSize) //Delete - //{ - // page.Index++; - // AddPageRowOffset(page, -PageSize); - //} - //else if (page.Rows[0].Index <= -PageSize) //Delete - //{ - // page.Index--; - // AddPageRowOffset(page, PageSize); - //} return page; } - private void AddPageRowOffset(PageIndex page, short offset) { - for (int r = 0; r < page.RowCount; r++) { - page.Rows[r].Index += offset; - } - } - private void AddPage(ColumnIndex column, int pos, short index) { AddPage(column, pos); column._pages[pos] = new() {
diff --git a/EPPlus/ConditionalFormatting/ExcelConditionalFormattingCollection.cs b/EPPlus/ConditionalFormatting/ExcelConditionalFormattingCollection.cs index 3c19a93..8d0ecf1 100644 --- a/EPPlus/ConditionalFormatting/ExcelConditionalFormattingCollection.cs +++ b/EPPlus/ConditionalFormatting/ExcelConditionalFormattingCollection.cs
@@ -67,15 +67,9 @@ public class ExcelConditionalFormattingCollection : XmlHelper, IEnumerable<IExcelConditionalFormattingRule> { - /****************************************************************************************/ - - private readonly List<IExcelConditionalFormattingRule> _rules = new(); private readonly ExcelWorksheet _worksheet; - /****************************************************************************************/ - - /// <summary> /// Initialize the <see cref="ExcelConditionalFormattingCollection"/> /// </summary> @@ -159,12 +153,6 @@ } } - /****************************************************************************************/ - - - /// <summary> - /// - /// </summary> private void EnsureRootElementExists() { // Find the <worksheet> node if (_worksheet.WorksheetXml.DocumentElement == null) { @@ -173,15 +161,6 @@ } /// <summary> - /// GetRootNode - /// </summary> - /// <returns></returns> - private XmlNode GetRootNode() { - EnsureRootElementExists(); - return _worksheet.WorksheetXml.DocumentElement; - } - - /// <summary> /// Validates address - not empty (collisions are allowded) /// </summary> /// <param name="address"></param> @@ -212,9 +191,6 @@ return lastPriority + 1; } - /****************************************************************************************/ - - /// <summary> /// Number of validations /// </summary> @@ -322,9 +298,6 @@ return _rules.Find(x => x.Priority == priority); } - /****************************************************************************************/ - - /// <summary> /// Add rule (internal) /// </summary>
diff --git a/EPPlus/ConditionalFormatting/ExcelConditionalFormattingColorScaleValue.cs b/EPPlus/ConditionalFormatting/ExcelConditionalFormattingColorScaleValue.cs index 1f1bda6..a8585f0 100644 --- a/EPPlus/ConditionalFormatting/ExcelConditionalFormattingColorScaleValue.cs +++ b/EPPlus/ConditionalFormatting/ExcelConditionalFormattingColorScaleValue.cs
@@ -41,16 +41,10 @@ /// Describes the values of the interpolation points in a gradient scale. /// </summary> public class ExcelConditionalFormattingColorScaleValue : XmlHelper { - /****************************************************************************************/ - - private eExcelConditionalFormattingValueObjectPosition _position; private eExcelConditionalFormattingRuleType _ruleType; private readonly ExcelWorksheet _worksheet; - /****************************************************************************************/ - - /// <summary> /// Initialize the cfvo (§18.3.1.11) node /// </summary> @@ -213,9 +207,6 @@ null, namespaceManager) {} - /****************************************************************************************/ - - /// <summary> /// Get the node order (1, 2 ou 3) according to the Position (Low, Middle and High) /// and the Rule Type (TwoColorScale ou ThreeColorScale). @@ -288,9 +279,6 @@ TopNode = currentTopNode; } - /****************************************************************************************/ - - /// <summary> /// /// </summary> @@ -446,10 +434,8 @@ CreateNodeByOrdem( eExcelConditionalFormattingValueObjectNodeType.Cfvo, ExcelConditionalFormattingConstants.Paths._valAttribute, - (value == null) ? string.Empty : value); + value ?? string.Empty); } } } - - /****************************************************************************************/ }
diff --git a/EPPlus/ConditionalFormatting/ExcelConditionalFormattingHelper.cs b/EPPlus/ConditionalFormatting/ExcelConditionalFormattingHelper.cs index 41fbe30..0ea9a45 100644 --- a/EPPlus/ConditionalFormatting/ExcelConditionalFormattingHelper.cs +++ b/EPPlus/ConditionalFormatting/ExcelConditionalFormattingHelper.cs
@@ -85,7 +85,7 @@ public static string GetAttributeString(XmlNode node, string attribute) { try { var value = node.Attributes[attribute].Value; - return (value == null) ? string.Empty : value; + return value ?? string.Empty; } catch { return string.Empty; }
diff --git a/EPPlus/ConditionalFormatting/ExcelConditionalFormattingIconDatabarValue.cs b/EPPlus/ConditionalFormatting/ExcelConditionalFormattingIconDatabarValue.cs index 2e080d2..bffef35 100644 --- a/EPPlus/ConditionalFormatting/ExcelConditionalFormattingIconDatabarValue.cs +++ b/EPPlus/ConditionalFormatting/ExcelConditionalFormattingIconDatabarValue.cs
@@ -42,15 +42,9 @@ /// Describes the values of the interpolation points in a gradient scale. /// </summary> public class ExcelConditionalFormattingIconDataBarValue : XmlHelper { - /****************************************************************************************/ - - private eExcelConditionalFormattingRuleType _ruleType; private readonly ExcelWorksheet _worksheet; - /****************************************************************************************/ - - /// <summary> /// Initialize the cfvo (§18.3.1.11) node /// </summary> @@ -213,11 +207,6 @@ XmlNamespaceManager namespaceManager) : this(type, 0, null, ruleType, address, priority, worksheet, null, namespaceManager) {} - /****************************************************************************************/ - - /****************************************************************************************/ - - /// <summary> /// /// </summary> @@ -296,6 +285,4 @@ } } } - - /****************************************************************************************/ }
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAboveAverage.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAboveAverage.cs index 6e82c2f..cf90b06 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAboveAverage.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAboveAverage.cs
@@ -57,7 +57,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAboveOrEqualAverage.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAboveOrEqualAverage.cs index 60a89d0..dcbf944 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAboveOrEqualAverage.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAboveOrEqualAverage.cs
@@ -58,7 +58,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAboveStdDev.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAboveStdDev.cs index 0883462..bd905e1 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAboveStdDev.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAboveStdDev.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAverageGroup.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAverageGroup.cs index cebdb51..34076ba 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAverageGroup.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAverageGroup.cs
@@ -62,7 +62,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) {} + namespaceManager ?? worksheet.NameSpaceManager) {} /// <summary> ///
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBeginsWith.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBeginsWith.cs index 9dc918e..d8cdd26 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBeginsWith.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBeginsWith.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBelowAverage.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBelowAverage.cs index be13fa3..ef68fc1 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBelowAverage.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBelowAverage.cs
@@ -57,7 +57,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBelowOrEqualAverage.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBelowOrEqualAverage.cs index 39eb327..4d8cd67 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBelowOrEqualAverage.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBelowOrEqualAverage.cs
@@ -58,7 +58,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBelowStdDev.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBelowStdDev.cs index b2419f6..8291319 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBelowStdDev.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBelowStdDev.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBetween.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBetween.cs index b27a308..fb1bb73 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBetween.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBetween.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBottom.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBottom.cs index 4b23f49..ae9e861 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBottom.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBottom.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBottomPercent.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBottomPercent.cs index 494078d..719901f 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBottomPercent.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingBottomPercent.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingContainsBlanks.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingContainsBlanks.cs index 16ea6c2..d5eafe0 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingContainsBlanks.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingContainsBlanks.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingContainsErrors.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingContainsErrors.cs index 5c743dc..f5d65f9 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingContainsErrors.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingContainsErrors.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingContainsText.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingContainsText.cs index 88a4d43..ed433cc 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingContainsText.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingContainsText.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDataBar.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDataBar.cs index ed32ace..2a80337 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDataBar.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDataBar.cs
@@ -64,7 +64,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { SchemaNodeOrder = new[] { "cfvo", "color" }; //Create the <dataBar> node inside the <cfRule> node if (itemElementNode != null && itemElementNode.HasChildNodes) {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDuplicateValues.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDuplicateValues.cs index 1231fc9..ecba659 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDuplicateValues.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDuplicateValues.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) {} + namespaceManager ?? worksheet.NameSpaceManager) {} /// <summary> ///
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingEndsWith.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingEndsWith.cs index d02ed50..39d2a2b 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingEndsWith.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingEndsWith.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingEqual.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingEqual.cs index 8a6ed42..ddade06 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingEqual.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingEqual.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingExpression.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingExpression.cs index 8ba9823..ce887c5 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingExpression.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingExpression.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingFiveIconSet.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingFiveIconSet.cs index 8c557d7..e75f49a 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingFiveIconSet.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingFiveIconSet.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode != null && itemElementNode.HasChildNodes) { XmlNode iconNode4 = TopNode.SelectSingleNode( "d:iconSet/d:cfvo[position()=4]",
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingFourIconSet.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingFourIconSet.cs index 14430b9..10bd1b3 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingFourIconSet.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingFourIconSet.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode != null && itemElementNode.HasChildNodes) { XmlNode iconNode4 = TopNode.SelectSingleNode( "d:iconSet/d:cfvo[position()=4]",
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingGreaterThan.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingGreaterThan.cs index 2e3d9ee..9e57c1e 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingGreaterThan.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingGreaterThan.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingGreaterThanOrEqual.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingGreaterThanOrEqual.cs index 6a19464..1a83939 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingGreaterThanOrEqual.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingGreaterThanOrEqual.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLast7Days.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLast7Days.cs index e2593d3..100f6da 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLast7Days.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLast7Days.cs
@@ -57,7 +57,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLastMonth.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLastMonth.cs index 1d31a44..3888e32 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLastMonth.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLastMonth.cs
@@ -57,7 +57,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLastWeek.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLastWeek.cs index 05c6513..9edbe40 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLastWeek.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLastWeek.cs
@@ -57,7 +57,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLessThan.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLessThan.cs index de178ec..5695da9 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLessThan.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLessThan.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLessThanOrEqual.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLessThanOrEqual.cs index 7c43a2e..3e54630 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLessThanOrEqual.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingLessThanOrEqual.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNextMonth.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNextMonth.cs index 3d756f4..a7a23e6 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNextMonth.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNextMonth.cs
@@ -57,7 +57,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNextWeek.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNextWeek.cs index 95726a1..1c01b87 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNextWeek.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNextWeek.cs
@@ -57,7 +57,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotBetween.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotBetween.cs index 71c565c..afa0de5 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotBetween.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotBetween.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotContainsBlanks.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotContainsBlanks.cs index b0e06b2..babf13b 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotContainsBlanks.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotContainsBlanks.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotContainsErrors.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotContainsErrors.cs index 7d42bd3..e6fa828 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotContainsErrors.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotContainsErrors.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotContainsText.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotContainsText.cs index 279d6b4..1b86511 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotContainsText.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotContainsText.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotEqual.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotEqual.cs index e882682..8782151 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotEqual.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingNotEqual.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThisMonth.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThisMonth.cs index 6104959..db86666 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThisMonth.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThisMonth.cs
@@ -57,7 +57,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThisWeek.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThisWeek.cs index a42007d..1635e36 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThisWeek.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThisWeek.cs
@@ -57,7 +57,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThreeColorScale.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThreeColorScale.cs index a63bf04..fa0574e 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThreeColorScale.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThreeColorScale.cs
@@ -61,7 +61,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { // Create the <colorScale> node inside the <cfRule> node var colorScaleNode = CreateComplexNode( Node,
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThreeIconSet.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThreeIconSet.cs index cc0a2ad..2b8b27e 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThreeIconSet.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThreeIconSet.cs
@@ -49,7 +49,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) {} + namespaceManager ?? worksheet.NameSpaceManager) {} } /// <summary> @@ -80,7 +80,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode != null && itemElementNode.HasChildNodes) { int pos = 1; foreach (XmlNode node in itemElementNode.SelectNodes("d:iconSet/d:cfvo", NameSpaceManager)) {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTimePeriodGroup.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTimePeriodGroup.cs index f8ebade..52fe1ab 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTimePeriodGroup.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTimePeriodGroup.cs
@@ -62,7 +62,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) {} + namespaceManager ?? worksheet.NameSpaceManager) {} /// <summary> ///
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingToday.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingToday.cs index 6b99262..b2d1755 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingToday.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingToday.cs
@@ -57,7 +57,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTomorrow.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTomorrow.cs index 6b5aa92..fcfab71 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTomorrow.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTomorrow.cs
@@ -57,7 +57,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTop.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTop.cs index 95697d0..5672d2d 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTop.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTop.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTopPercent.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTopPercent.cs index 929369d..0d4a06c 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTopPercent.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTopPercent.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTwoColorScale.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTwoColorScale.cs index 29a5a9e..69ee8b1 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTwoColorScale.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTwoColorScale.cs
@@ -71,7 +71,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { // Create the <colorScale> node inside the <cfRule> node var colorScaleNode = CreateComplexNode( Node,
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingUniqueValues.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingUniqueValues.cs index ef4d72e..ff0ba0d 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingUniqueValues.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingUniqueValues.cs
@@ -60,7 +60,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) {} + namespaceManager ?? worksheet.NameSpaceManager) {} /// <summary> ///
diff --git a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingYesterday.cs b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingYesterday.cs index 158948c..a5701ec 100644 --- a/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingYesterday.cs +++ b/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingYesterday.cs
@@ -57,7 +57,7 @@ priority, worksheet, itemElementNode, - (namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager) { + namespaceManager ?? worksheet.NameSpaceManager) { if (itemElementNode == null) //Set default values and create attributes if needed {
diff --git a/EPPlus/DataValidation/ExcelDataValidation.cs b/EPPlus/DataValidation/ExcelDataValidation.cs index 0f74ed9..78b6259 100644 --- a/EPPlus/DataValidation/ExcelDataValidation.cs +++ b/EPPlus/DataValidation/ExcelDataValidation.cs
@@ -93,7 +93,7 @@ ExcelDataValidationType validationType, XmlNode itemElementNode, XmlNamespaceManager namespaceManager) - : base(namespaceManager != null ? namespaceManager : worksheet.NameSpaceManager) { + : base(namespaceManager ?? worksheet.NameSpaceManager) { Require.Argument(address).IsNotNullOrEmpty("address"); address = CheckAndFixRangeAddress(address); if (itemElementNode == null) {
diff --git a/EPPlus/DataValidation/ExcelDataValidationCollection.cs b/EPPlus/DataValidation/ExcelDataValidationCollection.cs index 76c07a3..4518881 100644 --- a/EPPlus/DataValidation/ExcelDataValidationCollection.cs +++ b/EPPlus/DataValidation/ExcelDataValidationCollection.cs
@@ -103,9 +103,6 @@ _validations.Add(ExcelDataValidationFactory.Create(type, worksheet, addr, node)); } } - if (_validations.Count > 0) { - OnValidationCountChanged(); - } } private void EnsureRootElementExists() { @@ -117,21 +114,6 @@ } } - private void OnValidationCountChanged() { - //if (TopNode != null) - //{ - // SetXmlNodeString("@count", _validations.Count.ToString()); - //} - } - - private XmlNode GetRootNode() { - EnsureRootElementExists(); - TopNode = _worksheet.WorksheetXml.SelectSingleNode( - _dataValidationPath, - _worksheet.NameSpaceManager); - return TopNode; - } - /// <summary> /// Validates address - not empty, collisions /// </summary> @@ -184,7 +166,6 @@ EnsureRootElementExists(); var item = new ExcelDataValidationAny(_worksheet, address, ExcelDataValidationType.Any); _validations.Add(item); - OnValidationCountChanged(); return item; } @@ -198,7 +179,6 @@ EnsureRootElementExists(); var item = new ExcelDataValidationInt(_worksheet, address, ExcelDataValidationType.Whole); _validations.Add(item); - OnValidationCountChanged(); return item; } @@ -213,7 +193,6 @@ EnsureRootElementExists(); var item = new ExcelDataValidationDecimal(_worksheet, address, ExcelDataValidationType.Decimal); _validations.Add(item); - OnValidationCountChanged(); return item; } @@ -228,7 +207,6 @@ EnsureRootElementExists(); var item = new ExcelDataValidationList(_worksheet, address, ExcelDataValidationType.List); _validations.Add(item); - OnValidationCountChanged(); return item; } @@ -242,7 +220,6 @@ EnsureRootElementExists(); var item = new ExcelDataValidationInt(_worksheet, address, ExcelDataValidationType.TextLength); _validations.Add(item); - OnValidationCountChanged(); return item; } @@ -259,7 +236,6 @@ address, ExcelDataValidationType.DateTime); _validations.Add(item); - OnValidationCountChanged(); return item; } @@ -268,7 +244,6 @@ EnsureRootElementExists(); var item = new ExcelDataValidationTime(_worksheet, address, ExcelDataValidationType.Time); _validations.Add(item); - OnValidationCountChanged(); return item; } @@ -282,7 +257,6 @@ EnsureRootElementExists(); var item = new ExcelDataValidationCustom(_worksheet, address, ExcelDataValidationType.Custom); _validations.Add(item); - OnValidationCountChanged(); return item; } @@ -293,17 +267,13 @@ /// <returns>True if remove succeeds, otherwise false</returns> /// <exception cref="ArgumentNullException">if <paramref name="item"/> is null</exception> public bool Remove(IExcelDataValidation item) { - if (!(item is ExcelDataValidation)) { + if (!(item is ExcelDataValidation validation)) { throw new InvalidCastException( "The supplied item must inherit OfficeOpenXml.DataValidation.ExcelDataValidation"); } Require.Argument(item).IsNotNull("item"); - TopNode.RemoveChild(((ExcelDataValidation)item).TopNode); - var retVal = _validations.Remove(item); - if (retVal) { - OnValidationCountChanged(); - } - return retVal; + TopNode.RemoveChild(validation.TopNode); + return _validations.Remove(validation); } /// <summary> @@ -317,8 +287,8 @@ /// <param name="index"></param> /// <returns></returns> public IExcelDataValidation this[int index] { - get { return _validations[index]; } - set { _validations[index] = value; } + get => _validations[index]; + set => _validations[index] = value; } /// <summary> @@ -367,16 +337,15 @@ public void RemoveAll(Predicate<IExcelDataValidation> match) { var matches = _validations.FindAll(match); foreach (var m in matches) { - if (!(m is ExcelDataValidation)) { + if (!(m is ExcelDataValidation validation)) { throw new InvalidCastException( "The supplied item must inherit OfficeOpenXml.DataValidation.ExcelDataValidation"); } TopNode .SelectSingleNode(_dataValidationPath.TrimStart('/'), NameSpaceManager) - .RemoveChild(((ExcelDataValidation)m).TopNode); + .RemoveChild(validation.TopNode); } _validations.RemoveAll(match); - OnValidationCountChanged(); } IEnumerator<IExcelDataValidation> IEnumerable<IExcelDataValidation>.GetEnumerator() {
diff --git a/EPPlus/DataValidation/ExcelDataValidationType.cs b/EPPlus/DataValidation/ExcelDataValidationType.cs index 50b8571..1c7465c 100644 --- a/EPPlus/DataValidation/ExcelDataValidationType.cs +++ b/EPPlus/DataValidation/ExcelDataValidationType.cs
@@ -173,10 +173,10 @@ /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { - if (!(obj is ExcelDataValidationType)) { + if (!(obj is ExcelDataValidationType type)) { return false; } - return ((ExcelDataValidationType)obj).Type == Type; + return type.Type == Type; } /// <summary>
diff --git a/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaDateTime.cs b/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaDateTime.cs index 5543046..3dbc85d 100644 --- a/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaDateTime.cs +++ b/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaDateTime.cs
@@ -47,8 +47,7 @@ : base(namespaceManager, topNode, formulaPath) { var value = GetXmlNodeString(formulaPath); if (!string.IsNullOrEmpty(value)) { - double oADate = default(double); - if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out oADate)) { + if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var oADate)) { Value = DateTime.FromOADate(oADate); } else { ExcelFormula = value;
diff --git a/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaDecimal.cs b/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaDecimal.cs index 67b921d..995c459 100644 --- a/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaDecimal.cs +++ b/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaDecimal.cs
@@ -49,8 +49,7 @@ : base(namespaceManager, topNode, formulaPath) { var value = GetXmlNodeString(formulaPath); if (!string.IsNullOrEmpty(value)) { - double dValue = default(double); - if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out dValue)) { + if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var dValue)) { Value = dValue; } else { ExcelFormula = value;
diff --git a/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaInt.cs b/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaInt.cs index 70dc8cc..6bd31d2 100644 --- a/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaInt.cs +++ b/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaInt.cs
@@ -45,8 +45,7 @@ : base(namespaceManager, topNode, formulaPath) { var value = GetXmlNodeString(formulaPath); if (!string.IsNullOrEmpty(value)) { - int intValue = default(int); - if (int.TryParse(value, out intValue)) { + if (int.TryParse(value, out var intValue)) { Value = intValue; } else { ExcelFormula = value;
diff --git a/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaTime.cs b/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaTime.cs index 38a8176..54d9844 100644 --- a/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaTime.cs +++ b/EPPlus/DataValidation/Formulas/ExcelDataValidationFormulaTime.cs
@@ -47,8 +47,7 @@ : base(namespaceManager, topNode, formulaPath) { var value = GetXmlNodeString(formulaPath); if (!string.IsNullOrEmpty(value)) { - decimal time = default(decimal); - if (decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out time)) { + if (decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var time)) { Value = new(time); } else { Value = new();
diff --git a/EPPlus/Drawing/Vml/ExcelVmlDrawingComment.cs b/EPPlus/Drawing/Vml/ExcelVmlDrawingComment.cs index 560529e..3392fc7 100644 --- a/EPPlus/Drawing/Vml/ExcelVmlDrawingComment.cs +++ b/EPPlus/Drawing/Vml/ExcelVmlDrawingComment.cs
@@ -140,7 +140,7 @@ /// If the drawing object is visible. /// </summary> public bool Visible { - get { return (TopNode.SelectSingleNode(_visiblePath, NameSpaceManager) != null); } + get => (TopNode.SelectSingleNode(_visiblePath, NameSpaceManager) != null); set { if (value) { CreateNode(_visiblePath); @@ -153,7 +153,6 @@ } private const string _backgroundcolorPath = "@fillcolor"; - private const string _backgroundcolor2Path = "v:fill/@color2"; /// <summary> /// Background color @@ -167,12 +166,11 @@ if (col.StartsWith("#")) { col = col.Substring(1, col.Length - 1); } - int res; if (int.TryParse( col, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, - out res)) { + out var res)) { return Color.FromArgb(res); } return Color.Empty; @@ -233,12 +231,11 @@ if (col.StartsWith("#")) { col = col.Substring(1, col.Length - 1); } - int res; if (int.TryParse( col, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, - out res)) { + out var res)) { return Color.FromArgb(res); } return Color.Empty; @@ -264,13 +261,12 @@ wt = wt.Substring(0, wt.Length - 2); } - Single ret; - if (Single.TryParse(wt, NumberStyles.Any, CultureInfo.InvariantCulture, out ret)) { + if (Single.TryParse(wt, NumberStyles.Any, CultureInfo.InvariantCulture, out var ret)) { return ret; } return 0; } - set { SetXmlNodeString(_linewidthPath, value.ToString(CultureInfo.InvariantCulture) + "pt"); } + set => SetXmlNodeString(_linewidthPath, value.ToString(CultureInfo.InvariantCulture) + "pt"); } ///// <summary> @@ -336,15 +332,13 @@ /// </summary> public bool AutoFit { get { - string value; - GetStyle(GetXmlNodeString(_textboxStylePath), "mso-fit-shape-to-text", out value); + GetStyle(GetXmlNodeString(_textboxStylePath), "mso-fit-shape-to-text", out var value); return value == "t"; } - set { + set => SetXmlNodeString( _textboxStylePath, SetStyle(GetXmlNodeString(_textboxStylePath), "mso-fit-shape-to-text", value ? "t" : "")); - } } private const string _lockedPath = "x:ClientData/x:Locked"; @@ -353,8 +347,8 @@ /// If the object is locked when the sheet is protected /// </summary> public bool Locked { - get { return GetXmlNodeBool(_lockedPath, false); } - set { SetXmlNodeBool(_lockedPath, value, false); } + get => GetXmlNodeBool(_lockedPath, false); + set => SetXmlNodeBool(_lockedPath, value, false); } private const string _lockTextPath = "x:ClientData/x:LockText"; @@ -363,8 +357,8 @@ /// Specifies that the object's text is locked /// </summary> public bool LockText { - get { return GetXmlNodeBool(_lockTextPath, false); } - set { SetXmlNodeBool(_lockTextPath, value, false); } + get => GetXmlNodeBool(_lockTextPath, false); + set => SetXmlNodeBool(_lockTextPath, value, false); } private ExcelVmlDrawingPosition _from; @@ -401,14 +395,12 @@ private const string _stylePath = "@style"; internal string Style { - get { return GetXmlNodeString(_stylePath); } - set { SetXmlNodeString(_stylePath, value); } + get => GetXmlNodeString(_stylePath); + set => SetXmlNodeString(_stylePath, value); } ulong IRangeId.RangeID { - get { - return ExcelCellBase.GetCellId(Range.Worksheet.SheetID, Range.Start.Row, Range.Start.Column); - } + get => ExcelCellBase.GetCellId(Range.Worksheet.SheetID, Range.Start.Row, Range.Start.Column); set {} } }
diff --git a/EPPlus/Drawing/Vml/ExcelVmlDrawingCommentCollection.cs b/EPPlus/Drawing/Vml/ExcelVmlDrawingCommentCollection.cs index 6a908e3..deb294c 100644 --- a/EPPlus/Drawing/Vml/ExcelVmlDrawingCommentCollection.cs +++ b/EPPlus/Drawing/Vml/ExcelVmlDrawingCommentCollection.cs
@@ -158,8 +158,7 @@ if (_nextID == 0) { foreach (ExcelVmlDrawingComment draw in this) { if (draw.Id.Length > 3 && draw.Id.StartsWith("vml")) { - int id; - if (int.TryParse(draw.Id.Substring(3, draw.Id.Length - 3), out id)) { + if (int.TryParse(draw.Id.Substring(3, draw.Id.Length - 3), out var id)) { if (id > _nextID) { _nextID = id; } @@ -177,9 +176,7 @@ return _drawings.ContainsKey(rangeId); } - internal int Count { - get { return _drawings.Count; } - } + internal int Count => _drawings.Count; public IEnumerator GetEnumerator() { return _drawings;
diff --git a/EPPlus/Drawing/Vml/ExcelVmlDrawingPosition.cs b/EPPlus/Drawing/Vml/ExcelVmlDrawingPosition.cs index 3d02863..294f9b2 100644 --- a/EPPlus/Drawing/Vml/ExcelVmlDrawingPosition.cs +++ b/EPPlus/Drawing/Vml/ExcelVmlDrawingPosition.cs
@@ -93,8 +93,7 @@ string anchor = GetXmlNodeString("x:Anchor"); string[] numbers = anchor.Split(','); if (numbers.Length == 8) { - int ret; - if (int.TryParse(numbers[_startPos + pos], out ret)) { + if (int.TryParse(numbers[_startPos + pos], out var ret)) { return ret; } }
diff --git a/EPPlus/EPPlusSDK.csproj b/EPPlus/EPPlusSDK.csproj index 00f19ed..a26851d 100644 --- a/EPPlus/EPPlusSDK.csproj +++ b/EPPlus/EPPlusSDK.csproj
@@ -4,17 +4,9 @@ <RootNamespace>OfficeOpenXml</RootNamespace> <AssemblyName>EPPlus</AssemblyName> <PackageId>Appsheet.EPPlus</PackageId> - <Version>1.0.5</Version> - <DefaultItemExcludes>$(DefaultItemExcludes);Properties/AssemblyInfo.cs;FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/**;FormulaParsing/LexicalAnalysis/TokenHandler.cs;FormulaParsing/Excel/Functions/Math/Rank.cs</DefaultItemExcludes> - <DefineConstants>Core;STANDARD20</DefineConstants> - <ImplicitUsings>disable</ImplicitUsings> + <Version>1.0.6</Version> </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.CSharp" Version="4.7.0"/> - <PackageReference Include="System.CodeDom" Version="5.0.0"/> <PackageReference Include="System.Drawing.Common" Version="6.0.0"/> - <PackageReference Include="System.Security.Cryptography.Pkcs" Version="5.0.1"/> - <PackageReference Include="System.Security.Permissions" Version="5.0.0"/> - <PackageReference Include="System.Text.Encoding.CodePages" Version="5.0.0"/> </ItemGroup> </Project>
diff --git a/EPPlus/ExcelAddress.cs b/EPPlus/ExcelAddress.cs index 22fcf59..9a5f20d 100644 --- a/EPPlus/ExcelAddress.cs +++ b/EPPlus/ExcelAddress.cs
@@ -410,16 +410,12 @@ /// <summary> /// The address for the range /// </summary> - public virtual string Address { - get { return _address; } - } + public virtual string Address => _address; /// <summary> /// If the address is a defined name /// </summary> - public bool IsName { - get { return _fromRow < 0; } - } + public bool IsName => _fromRow < 0; /// <summary> /// Returns the address text @@ -444,11 +440,7 @@ } } - internal string AddressSpaceSeparated { - get { - return _address.Replace(',', ' '); //Conditional formatting and a few other places use space as separator for mulit addresses. - } - } + internal string AddressSpaceSeparated => _address.Replace(',', ' '); //Conditional formatting and a few other places use space as separator for mulit addresses. /// <summary> /// Validate the address @@ -460,15 +452,11 @@ } } - internal string WorkSheet { - get { return _ws; } - } + internal string WorkSheet => _ws; protected internal List<ExcelAddress> _addresses; - internal virtual List<ExcelAddress> Addresses { - get { return _addresses; } - } + internal virtual List<ExcelAddress> Addresses => _addresses; private bool ExtractAddress(string fullAddress) { var brackPos = new Stack<int>(); @@ -864,10 +852,8 @@ if (IsFormula(address)) { return AddressType.Formula; } - string wb, - ws, - intAddress; - if (SplitAddress(address, out wb, out ws, out intAddress)) { + string ws; + if (SplitAddress(address, out var wb, out ws, out var intAddress)) { if (intAddress.Contains( "[")) //Table reference { @@ -955,12 +941,10 @@ return false; } var cells = intAddress.Split(':'); - int fromRow, - toRow, - fromCol, + int toRow, toCol; - if (!GetRowCol(cells[0], out fromRow, out fromCol, false)) { + if (!GetRowCol(cells[0], out var fromRow, out var fromCol, false)) { return false; } if (cells.Length > 1) { @@ -1052,22 +1036,9 @@ return false; } - private static bool IsValidName(string address) { - if (Regex.IsMatch( - address, - "[^0-9./*-+,½!\"@#£%&/{}()\\[\\]=?`^~':;<>|][^/*-+,½!\"@#£%&/{}()\\[\\]=?`^~':;<>|]*")) { - return true; - } - return false; - } + public int Rows => _toRow - _fromRow + 1; - public int Rows { - get { return _toRow - _fromRow + 1; } - } - - public int Columns { - get { return _toCol - _fromCol + 1; } - } + public int Columns => _toCol - _fromCol + 1; internal bool IsMultiCell() { return (_fromRow < _fromCol || _fromCol < _toCol);
diff --git a/EPPlus/ExcelCellBase.cs b/EPPlus/ExcelCellBase.cs index 36e1450..df48cb3 100644 --- a/EPPlus/ExcelCellBase.cs +++ b/EPPlus/ExcelCellBase.cs
@@ -274,10 +274,8 @@ /// <param name="colIncr"></param> /// <returns></returns> private static string ToR1C1(string part, int row, int col, int rowIncr, int colIncr) { - int addrRow, - addrCol; string ret = "R"; - if (GetRowCol(part, out addrRow, out addrCol, false)) { + if (GetRowCol(part, out var addrRow, out var addrCol, false)) { if (addrRow == 0 || addrCol == 0) { return part; } @@ -299,16 +297,13 @@ } private static string ToR1C1_V1(string part, int row, int col, int rowIncr, int colIncr) { - int addrRow, - addrCol; - // Handle range expressions if ((part.Length > 1) && (part.IndexOf(':', 1) > 0)) { return RangeToR1C1_V1(part, row, col, rowIncr, colIncr); } string ret = "R"; - if (GetRowCol(part, out addrRow, out addrCol, false)) { + if (GetRowCol(part, out var addrRow, out var addrCol, false)) { if (addrRow == 0 || addrCol == 0) { return part; } @@ -352,13 +347,14 @@ int col, int rowIncr, int colIncr) { - int addrRow, - addrCol; - bool fixedRow, - fixedCol; - string result = ""; - if (GetRowCol_V1(part, out addrRow, out addrCol, false, out fixedRow, out fixedCol)) { + if (GetRowCol_V1( + part, + out var addrRow, + out var addrCol, + false, + out var fixedRow, + out var fixedCol)) { if (addrRow > 0) { result += "R"; if (fixedRow) { @@ -409,8 +405,7 @@ } int cStart = check.IndexOf("C"); - bool absoluteRow, - absoluteCol; + bool absoluteRow; if (cStart == -1) { int rNum = GetRc(part, row, out absoluteRow); if (rNum > int.MinValue) { @@ -419,7 +414,10 @@ return part; } else { int rNum = GetRc(part.Substring(1, cStart - 1), row, out absoluteRow); - int cNum = GetRc(part.Substring(cStart + 1, part.Length - cStart - 1), col, out absoluteCol); + int cNum = GetRc( + part.Substring(cStart + 1, part.Length - cStart - 1), + col, + out var absoluteCol); if (rNum > int.MinValue && cNum > int.MinValue) { return GetAddress(rNum, absoluteRow, cNum, absoluteCol); } @@ -585,8 +583,7 @@ } // Return number value - int result; - return (int.TryParse(value.Substring(0, length), out result)) ? result : Int32.MinValue; + return (int.TryParse(value.Substring(0, length), out var result)) ? result : Int32.MinValue; } private static string RangeToA1_V1(string part, int row, int col, int rowIncr, int colIncr) { @@ -603,98 +600,6 @@ return result; } - private static string RangeCellToA1_V1(string part, int row, int col, int rowIncr, int colIncr) { - int addrRow, - addrCol; - bool fixedRow, - fixedCol; - - string result = ""; - if (GetRowCol_V1(part, out addrRow, out addrCol, false, out fixedRow, out fixedCol)) { - if (addrRow > 0) { - result += "R"; - if (fixedRow) { - // Absolute row - result += addrRow.ToString(); - } else if (addrRow - row != 0) { - // Relative row - result += string.Format("[{0}]", addrRow - row); - } - } - - if (addrCol > 0) { - result += "C"; - if (fixedCol) { - // Absolute column - result += addrCol; - } else if (addrCol - col != 0) { - // Relative column - result += string.Format("[{0}]", addrCol - col); - } - } - return result; - } - return part; - } - - /// <summary> - /// Adds or subtracts a row or column to an address - /// </summary> - /// <param name="address"></param> - /// <param name="row"></param> - /// <param name="col"></param> - /// <param name="rowIncr"></param> - /// <param name="colIncr"></param> - /// <returns></returns> - private static string AddToRowColumnTranslator( - string address, - int row, - int col, - int rowIncr, - int colIncr) { - int fromRow, - fromCol; - if (address == "#REF!") { - return address; - } - if (GetRowCol(address, out fromRow, out fromCol, false)) { - if (fromRow == 0 || fromCol == 0) { - return address; - } - if (rowIncr != 0 && row != 0 && fromRow >= row && address.IndexOf('$', 1) == -1) { - if (fromRow < row - rowIncr) { - return "#REF!"; - } - - fromRow = fromRow + rowIncr; - } - - if (colIncr != 0 && col != 0 && fromCol >= col && address.StartsWith("$") == false) { - if (fromCol < col - colIncr) { - return "#REF!"; - } - - fromCol = fromCol + colIncr; - } - - address = GetAddress(fromRow, address.IndexOf('$', 1) > -1, fromCol, address.StartsWith("$")); - } - return address; - } - - /// <summary> - /// Returns with brackets if the value is negative - /// </summary> - /// <param name="v">The value</param> - /// <returns></returns> - private static string GetRcFmt(int v) { - return (v < 0 - ? string.Format("[{0}]", v) - : v > 0 - ? v.ToString() - : ""); - } - /// <summary> /// Get the offset value for RC format /// </summary> @@ -727,32 +632,6 @@ return int.MinValue; } - private static int GetRC_V1(string value, int offsetValue, out bool fixedAddr) { - if ((value == "") || (value == "R") || (value == "C")) { - // Relative address with no offset - fixedAddr = false; - return offsetValue; - } - int num; - if (value[1] == '[' - && value[value.Length - 1] - == ']') //Offset? - { - // Relative address - fixedAddr = false; - if (int.TryParse(value.Substring(2, value.Length - 3), out num)) { - return (offsetValue + num); - } - return int.MinValue; - } - // Absolute address - fixedAddr = true; - if (int.TryParse(value.Substring(1, value.Length - 1), out num)) { - return num; - } - return int.MinValue; - } - /// <summary> /// Returns the character representation of the numbered column /// </summary> @@ -1303,9 +1182,7 @@ public static bool IsValidCellAddress(string cellAddress) { bool result = false; try { - int row, - col; - if (GetRowColFromAddress(cellAddress, out row, out col)) { + if (GetRowColFromAddress(cellAddress, out var row, out var col)) { if (row > 0 && col > 0 && row <= ExcelPackage.MaxRows && col <= ExcelPackage.MaxColumns) { result = true; } else {
diff --git a/EPPlus/ExcelNamedRangeCollection.cs b/EPPlus/ExcelNamedRangeCollection.cs index 748b7e7..3584a54 100644 --- a/EPPlus/ExcelNamedRangeCollection.cs +++ b/EPPlus/ExcelNamedRangeCollection.cs
@@ -178,13 +178,9 @@ /// <remarks> /// Throws a KeyNotFoundException if the key is not in the collection. /// </remarks> - public ExcelNamedRange this[string name] { - get { return _list[_dic[name]]; } - } + public ExcelNamedRange this[string name] => _list[_dic[name]]; - public ExcelNamedRange this[int index] { - get { return _list[index]; } - } + public ExcelNamedRange this[int index] => _list[index]; /// <summary> /// Implement interface method IEnumerator<ExcelNamedRange> GetEnumerator()
diff --git a/EPPlus/ExcelProtectedRangeCollection.cs b/EPPlus/ExcelProtectedRangeCollection.cs index 728a3e4..fdc2053 100644 --- a/EPPlus/ExcelProtectedRangeCollection.cs +++ b/EPPlus/ExcelProtectedRangeCollection.cs
@@ -75,9 +75,7 @@ _baseList.RemoveAt(index); } - public ExcelProtectedRange this[int index] { - get { return _baseList[index]; } - } + public ExcelProtectedRange this[int index] => _baseList[index]; IEnumerator<ExcelProtectedRange> IEnumerable<ExcelProtectedRange>.GetEnumerator() { return _baseList.GetEnumerator();
diff --git a/EPPlus/ExcelRangeBase.cs b/EPPlus/ExcelRangeBase.cs index b94a638..b4e48a8 100644 --- a/EPPlus/ExcelRangeBase.cs +++ b/EPPlus/ExcelRangeBase.cs
@@ -137,7 +137,7 @@ _worksheet = xlWorksheet; _workbook = wb; if (string.IsNullOrEmpty(_ws)) { - _ws = (xlWorksheet == null ? null : xlWorksheet.Name); + _ws = xlWorksheet?.Name; } AddressChange += ExcelRangeBase_AddressChange; SetDelegate(); @@ -237,11 +237,6 @@ _worksheet._styles.SetValue(row, col, (int)value); } - private void Set_StyleName(object value, int row, int col) { - //_worksheet.Cell(row, col).SetNewStyleName(value.ToString(), _styleID); - _worksheet._styles.SetValue(row, col, _styleID); - } - private void Set_Value(object value, int row, int col) { //ExcelCell c = _worksheet.Cell(row, col); var sfi = _worksheet._formulas.GetValue(row, col); @@ -257,7 +252,7 @@ private void Set_Formula(object value, int row, int col) { //ExcelCell c = _worksheet.Cell(row, col); var f = _worksheet._formulas.GetValue(row, col); - if (f is int && (int)f >= 0) { + if (f is int i && i >= 0) { SplitFormulas(_worksheet.Cells[row, col]); } @@ -321,13 +316,13 @@ private void Set_HyperLink(object value, int row, int col) { //_worksheet.Cell(row, col).Hyperlink = value as Uri; - if (value is Uri) { - _worksheet._hyperLinks.SetValue(row, col, (Uri)value); + if (value is Uri uri) { + _worksheet._hyperLinks.SetValue(row, col, uri); - if (value is ExcelHyperLink) { - _worksheet._values.SetValue(row, col, ((ExcelHyperLink)value).Display); + if (uri is ExcelHyperLink link) { + _worksheet._values.SetValue(row, col, link.Display); } else { - _worksheet._values.SetValue(row, col, ((Uri)value).OriginalString); + _worksheet._values.SetValue(row, col, uri.OriginalString); } } else { _worksheet._hyperLinks.SetValue(row, col, null); @@ -629,18 +624,6 @@ } } - private bool IsInfinityValue(object value) { - double? valueAsDouble = value as double?; - - if (valueAsDouble.HasValue - && (double.IsNegativeInfinity(valueAsDouble.Value) - || double.IsPositiveInfinity(valueAsDouble.Value))) { - return true; - } - - return false; - } - private object GetValueArray() { ExcelAddressBase addr; if (_fromRow == 1 @@ -670,60 +653,11 @@ return v; } - private ExcelAddressBase GetAddressDim(ExcelRangeBase addr) { - int fromRow, - fromCol, - toRow, - toCol; - var d = _worksheet.Dimension; - fromRow = addr._fromRow < d._fromRow ? d._fromRow : addr._fromRow; - fromCol = addr._fromCol < d._fromCol ? d._fromCol : addr._fromCol; - - toRow = addr._toRow > d._toRow ? d._toRow : addr._toRow; - toCol = addr._toCol > d._toCol ? d._toCol : addr._toCol; - - if (addr._fromCol == fromRow && addr._toRow == toRow && addr._toCol == _toCol) { - return addr; - } - if (_fromRow > _toRow || _fromCol > _toCol) { - return null; - } - return new(fromRow, fromCol, toRow, toCol); - } - - private object GetSingleValue() { - if (IsRichText) { - return RichText.Text; - } - return _worksheet._values.GetValue(_fromRow, _fromCol); - } - /// <summary> /// Returns the formatted value. /// </summary> public string Text => GetFormattedText(false); - private void SetMinWidth(double minimumWidth, int fromCol, int toCol) { - var iterator = new CellsStoreEnumerator<object>(_worksheet._values, 0, fromCol, 0, toCol); - var prevCol = fromCol; - foreach (ExcelColumn col in iterator) { - col.Width = minimumWidth; - if (_worksheet.DefaultColWidth > minimumWidth && col.ColumnMin > prevCol) { - var newCol = _worksheet.Column(prevCol); - newCol.ColumnMax = col.ColumnMin - 1; - newCol.Width = minimumWidth; - } - prevCol = col.ColumnMax + 1; - } - if (_worksheet.DefaultColWidth > minimumWidth && prevCol < toCol) { - var newCol = _worksheet.Column(prevCol); - newCol.ColumnMax = toCol; - newCol.Width = minimumWidth; - } - } - - internal string TextForWidth => GetFormattedText(true); - private string GetFormattedText(bool forWidthCalc) { object v = Value; if (v == null) { @@ -775,20 +709,20 @@ var date = DateTime.FromOADate(d); return date.ToString(format, nf.Culture); } - } else if (v is DateTime) { + } else if (v is DateTime time) { if (nf.DataType == ExcelNumberFormatXml.eFormatType.DateTime) { - return ((DateTime)v).ToString(format, nf.Culture); + return time.ToString(format, nf.Culture); } - double d = ((DateTime)v).ToOADate(); + double d = time.ToOADate(); if (string.IsNullOrEmpty(nf.FractionFormat)) { return d.ToString(format, nf.Culture); } return nf.FormatFraction(d); - } else if (v is TimeSpan) { + } else if (v is TimeSpan span) { if (nf.DataType == ExcelNumberFormatXml.eFormatType.DateTime) { - return new DateTime(((TimeSpan)v).Ticks).ToString(format, nf.Culture); + return new DateTime(span.Ticks).ToString(format, nf.Culture); } - double d = (new DateTime(((TimeSpan)v).Ticks)).ToOADate(); + double d = (new DateTime(span.Ticks)).ToOADate(); if (string.IsNullOrEmpty(nf.FractionFormat)) { return d.ToString(format, nf.Culture); } @@ -1195,7 +1129,7 @@ for (int col = address._fromCol; col <= address._toCol; col++) { for (int row = address._fromRow; row <= address._toRow; row++) { var f = _worksheet._formulas.GetValue(row, col); - if (f is int && (int)f >= 0) { + if (f is int i && i >= 0) { SplitFormulas(address); return; } @@ -1208,8 +1142,7 @@ for (int col = address._fromCol; col <= address._toCol; col++) { for (int row = address._fromRow; row <= address._toRow; row++) { var f = _worksheet._formulas.GetValue(row, col); - if (f is int) { - int id = (int)f; + if (f is int id) { if (id >= 0 && !formulas.Contains(id)) { if (_worksheet._sharedFormulas[id].IsArray && Collide(_worksheet.Cells[_worksheet._sharedFormulas[id].Address]) @@ -1652,12 +1585,12 @@ _worksheet.Cells[row, col++].Value = item; } else { foreach (var t in members) { - if (t is PropertyInfo) { - _worksheet.Cells[row, col++].Value = ((PropertyInfo)t).GetValue(item, null); - } else if (t is FieldInfo) { - _worksheet.Cells[row, col++].Value = ((FieldInfo)t).GetValue(item); - } else if (t is MethodInfo) { - _worksheet.Cells[row, col++].Value = ((MethodInfo)t).Invoke(item, null); + if (t is PropertyInfo info) { + _worksheet.Cells[row, col++].Value = info.GetValue(item, null); + } else if (t is FieldInfo fieldInfo) { + _worksheet.Cells[row, col++].Value = fieldInfo.GetValue(item); + } else if (t is MethodInfo methodInfo) { + _worksheet.Cells[row, col++].Value = methodInfo.Invoke(item, null); } } } @@ -2308,24 +2241,6 @@ } } - private void DeleteCheckMergedCells(ExcelAddressBase range) { - var removeItems = new List<string>(); - foreach (var addr in Worksheet.MergedCells) { - var addrCol = range.Collide(new ExcelAddress(range.WorkSheet, addr)); - if (addrCol != eAddressCollition.No) { - if (addrCol == eAddressCollition.Inside) { - removeItems.Add(addr); - } else { - throw (new InvalidOperationException( - "Can't remove/overwrite a part of cells that are merged")); - } - } - } - foreach (var item in removeItems) { - Worksheet.MergedCells.Remove(item); - } - } - public void Dispose() {} //int _index;
diff --git a/EPPlus/ExcelRow.cs b/EPPlus/ExcelRow.cs index 3dfd422..bb94e2b 100644 --- a/EPPlus/ExcelRow.cs +++ b/EPPlus/ExcelRow.cs
@@ -87,9 +87,7 @@ /// <summary> /// Provides access to the node representing the row. /// </summary> - internal XmlNode Node { - get { return (_rowElement); } - } + internal XmlNode Node => (_rowElement); /// <summary> /// Allows the row to be hidden in the worksheet @@ -153,7 +151,7 @@ /// Sets the style for the entire column using a style name. /// </summary> public string StyleName { - get { return _styleName; } + get => _styleName; set { StyleID = _worksheet.Workbook.Styles.GetStyleIdFromName(value); _styleName = value; @@ -164,8 +162,8 @@ /// Sets the style for the entire row using the style ID. /// </summary> public int StyleID { - get { return _worksheet._styles.GetValue(Row, 0); } - set { _worksheet._styles.SetValue(Row, 0, value); } + get => _worksheet._styles.GetValue(Row, 0); + set => _worksheet._styles.SetValue(Row, 0, value); } /// <summary> @@ -237,14 +235,8 @@ /// The Style applied to the whole row. Only effekt cells with no individual style set. /// Use ExcelRange object if you want to set specific styles. /// </summary> - public ExcelStyle Style { - get { - return _worksheet.Workbook.Styles.GetStyleObject( - StyleID, - _worksheet.PositionID, - Row + ":" + Row); - } - } + public ExcelStyle Style => + _worksheet.Workbook.Styles.GetStyleObject(StyleID, _worksheet.PositionID, Row + ":" + Row); /// <summary> /// Adds a manual page break after the row. @@ -264,8 +256,8 @@ } public bool Merged { - get { return _worksheet.MergedCells[Row, 0] != null; } - set { _worksheet.MergedCells.Add(new(Row, 1, Row, ExcelPackage.MaxColumns), true); } + get => _worksheet.MergedCells[Row, 0] != null; + set => _worksheet.MergedCells.Add(new(Row, 1, Row, ExcelPackage.MaxColumns), true); } internal static ulong GetRowId(int sheetId, int row) { @@ -274,8 +266,8 @@ [Obsolete] ulong IRangeId.RangeID { - get { return RowID; } - set { Row = ((int)(value >> 29)); } + get => RowID; + set => Row = ((int)(value >> 29)); } /// <summary>
diff --git a/EPPlus/ExcelStyleCollection.cs b/EPPlus/ExcelStyleCollection.cs index 2e2d203..b544547 100644 --- a/EPPlus/ExcelStyleCollection.cs +++ b/EPPlus/ExcelStyleCollection.cs
@@ -69,9 +69,7 @@ public T this[int positionId] => _list[positionId]; - public int Count { - get { return _list.Count; } - } + public int Count => _list.Count; //internal int Add(T item) //{
diff --git a/EPPlus/ExcelStyles.cs b/EPPlus/ExcelStyles.cs index 8c786e0..9f1b283 100644 --- a/EPPlus/ExcelStyles.cs +++ b/EPPlus/ExcelStyles.cs
@@ -750,14 +750,6 @@ //throw(new Exception("Named style does not exist")); } - private int GetXmlNodeInt(XmlNode node) { - int i; - if (int.TryParse(GetXmlNode(node), out i)) { - return i; - } - return 0; - } - private string GetXmlNode(XmlNode node) { if (node == null) { return "";
diff --git a/EPPlus/ExcelWorkbook.cs b/EPPlus/ExcelWorkbook.cs index 3bc05dd..3331644 100644 --- a/EPPlus/ExcelWorkbook.cs +++ b/EPPlus/ExcelWorkbook.cs
@@ -174,9 +174,8 @@ foreach (XmlElement elem in nl) { string fullAddress = elem.InnerText; - int localSheetId; ExcelWorksheet nameWorksheet; - if (!int.TryParse(elem.GetAttribute("localSheetId"), out localSheetId)) { + if (!int.TryParse(elem.GetAttribute("localSheetId"), out var localSheetId)) { localSheetId = -1; nameWorksheet = null; } else { @@ -191,8 +190,7 @@ int end = fullAddress.IndexOf("]", start); if (start >= 0 && end >= 0) { string externalIndex = fullAddress.Substring(start + 1, end - start - 1); - int index; - if (int.TryParse(externalIndex, out index)) { + if (int.TryParse(externalIndex, out var index)) { if (index > 0 && index <= _externalReferences.Count) { fullAddress = fullAddress.Substring(0, start) @@ -214,7 +212,6 @@ .AddressType .ExternalAddress) //A value or a formula { - double value; range = new(this, nameWorksheet, elem.GetAttribute("name"), true); if (nameWorksheet == null) { namedRange = _names.Add(elem.GetAttribute("name"), range); @@ -230,7 +227,7 @@ fullAddress, NumberStyles.Any, CultureInfo.InvariantCulture, - out value)) { + out var value)) { namedRange.NameValue = value; } else { //if (addressType == ExcelAddressBase.AddressType.ExternalAddress || addressType == ExcelAddressBase.AddressType.ExternalName) @@ -378,8 +375,8 @@ private const string _codeModuleNamePath = "d:workbookPr/@codeName"; internal string CodeModuleName { - get { return GetXmlNodeString(_codeModuleNamePath); } - set { SetXmlNodeString(_codeModuleNamePath, value); } + get => GetXmlNodeString(_codeModuleNamePath); + set => SetXmlNodeString(_codeModuleNamePath, value); } internal void CodeNameChange(string value) { @@ -395,7 +392,7 @@ /// This option was included in Microsoft Excel for Windows to make it compatible with Excel for the Macintosh, which defaults to January 2, 1904. /// </summary> public bool Date1904 { - get { return GetXmlNodeBool(_date1904Path, false); } + get => GetXmlNodeBool(_date1904Path, false); set { if (Date1904 != value) { // Like Excel when the option it's changed update it all cells with Date format @@ -445,7 +442,6 @@ StreamWriter stream = new StreamWriter( partWorkbook.GetStream(FileMode.Create, FileAccess.Write)); _workbookXml.Save(stream); - //stream.Close(); } } @@ -502,7 +498,7 @@ } return (_stylesXml); } - set { _stylesXml = value; } + set => _stylesXml = value; } /// <summary> @@ -570,8 +566,8 @@ /// <remarks>This property is always true for both new workbooks and loaded templates(on load). If this is not the wanted behavior set this property to false.</remarks> /// </summary> public bool FullCalcOnLoad { - get { return GetXmlNodeBool(_fullCalcOnLoadPath); } - set { SetXmlNodeBool(_fullCalcOnLoadPath, value); } + get => GetXmlNodeBool(_fullCalcOnLoadPath); + set => SetXmlNodeBool(_fullCalcOnLoadPath, value); } /// <summary> @@ -762,9 +758,8 @@ elem.InnerText = Convert .ToDouble(name.NameValue, CultureInfo.InvariantCulture) .ToString("R15", CultureInfo.InvariantCulture); - } else if (name.NameValue is DateTime) { - elem.InnerText = - ((DateTime)name.NameValue).ToOADate().ToString(CultureInfo.InvariantCulture); + } else if (name.NameValue is DateTime time) { + elem.InnerText = time.ToOADate().ToString(CultureInfo.InvariantCulture); } else { elem.InnerText = "\"" + name.NameValue + "\""; }
diff --git a/EPPlus/ExcelWorksheet.cs b/EPPlus/ExcelWorksheet.cs index 85a6ccd..c561c33 100644 --- a/EPPlus/ExcelWorksheet.cs +++ b/EPPlus/ExcelWorksheet.cs
@@ -697,7 +697,6 @@ } } - private const string _tabColorPath = "d:sheetPr/d:tabColor/@rgb"; private const string _codeModuleNamePath = "d:sheetPr/@codeName"; internal string CodeModuleName { @@ -785,8 +784,7 @@ LoadColPageBreakes(xr); //...then the rest of the Xml is extracted and loaded into the WorksheetXml document. stream.Seek(0, SeekOrigin.Begin); - Encoding encoding; - xml = GetWorkSheetXml(stream, start, end, out encoding); + xml = GetWorkSheetXml(stream, start, end, out var encoding); //first char is invalid sometimes?? if (xml[0] != '<') { @@ -824,8 +822,7 @@ while (xr.Read()) { if (xr.LocalName == "brk") { if (xr.NodeType == XmlNodeType.Element) { - int id; - if (int.TryParse(xr.GetAttribute("id"), out id)) { + if (int.TryParse(xr.GetAttribute("id"), out var id)) { Row(id).PageBreak = true; } } @@ -842,8 +839,7 @@ while (xr.Read()) { if (xr.LocalName == "brk") { if (xr.NodeType == XmlNodeType.Element) { - int id; - if (int.TryParse(xr.GetAttribute("id"), out id)) { + if (int.TryParse(xr.GetAttribute("id"), out var id)) { Column(id).PageBreak = true; } } @@ -1014,9 +1010,8 @@ xr.GetAttribute("hidden") != null && xr.GetAttribute("hidden") == "1" ? true : false; _values.SetValue(0, min, col); - int style; if (!(xr.GetAttribute("style") == null - || !int.TryParse(xr.GetAttribute("style"), out style))) { + || !int.TryParse(xr.GetAttribute("style"), out var style))) { _styles.SetValue(0, min, style); } } @@ -1025,23 +1020,6 @@ } /// <summary> - /// Read until the node is found. If not found the xmlreader is reseted. - /// </summary> - /// <param name="xr">The reader</param> - /// <param name="nodeText">Text to search for</param> - /// <param name="altNode">Alternative text to search for</param> - /// <returns></returns> - private static bool ReadXmlReaderUntil(XmlTextReader xr, string nodeText, string altNode) { - do { - if (xr.LocalName == nodeText || xr.LocalName == altNode) { - return true; - } - } while (xr.Read()); - xr.Close(); - return false; - } - - /// <summary> /// Load Hyperlinks /// </summary> /// <param name="xr">The reader</param> @@ -1051,16 +1029,12 @@ } while (xr.Read()) { if (xr.LocalName == "hyperlink") { - int fromRow, - fromCol, - toRow, - toCol; ExcelCellBase.GetRowColFromAddress( xr.GetAttribute("ref"), - out fromRow, - out fromCol, - out toRow, - out toCol); + out var fromRow, + out var fromCol, + out int toRow, + out var toCol); ExcelHyperLink hl = null; if (xr.GetAttribute("id", ExcelPackage._schemaRelationships) != null) { var rId = xr.GetAttribute("id", ExcelPackage._schemaRelationships); @@ -1429,8 +1403,7 @@ && nf <= 47)) // Duration { - double res; - if (double.TryParse(v, NumberStyles.Any, CultureInfo.InvariantCulture, out res)) { + if (double.TryParse(v, NumberStyles.Any, CultureInfo.InvariantCulture, out var res)) { if (Workbook.Date1904) { res += ExcelWorkbook._date1904Offset; } @@ -1451,8 +1424,7 @@ || (nf == 22)) // DateTime { - double res; - if (double.TryParse(v, NumberStyles.Any, CultureInfo.InvariantCulture, out res)) { + if (double.TryParse(v, NumberStyles.Any, CultureInfo.InvariantCulture, out var res)) { if (Workbook.Date1904) { res += ExcelWorkbook._date1904Offset; } @@ -1469,8 +1441,7 @@ _values.SetValue(row, col, v); } } else { - double d; - if (double.TryParse(v, NumberStyles.Any, CultureInfo.InvariantCulture, out d)) { + if (double.TryParse(v, NumberStyles.Any, CultureInfo.InvariantCulture, out var d)) { _values.SetValue(row, col, d); } else { // Cope with Google Sheets export of cells having a formula. @@ -1727,12 +1698,15 @@ /// <param name="selectSheet">Make the sheet active</param> public void Select(string address, bool selectSheet) { CheckSheetType(); - int fromCol, - fromRow, - toCol, + int toCol, toRow; //Get rows and columns and validate as well - ExcelCellBase.GetRowColFromAddress(address, out fromRow, out fromCol, out toRow, out toCol); + ExcelCellBase.GetRowColFromAddress( + address, + out var fromRow, + out var fromCol, + out toRow, + out toCol); if (selectSheet) { View.TabSelected = true; @@ -1937,8 +1911,8 @@ var csec = new CellsStoreEnumerator<object>(_values, 0, 1, 0, ExcelPackage.MaxColumns); var lst = new List<ExcelColumn>(); foreach (var col in csec) { - if (col is ExcelColumn) { - lst.Add((ExcelColumn)col); + if (col is ExcelColumn column) { + lst.Add(column); } } @@ -2081,246 +2055,6 @@ } } - private void FixSharedFormulasRows(int position, int rows) { - List<Formulas> added = new List<Formulas>(); - List<Formulas> deleted = new List<Formulas>(); - - foreach (int id in _sharedFormulas.Keys) { - var f = _sharedFormulas[id]; - int fromCol, - fromRow, - toCol, - toRow; - - ExcelCellBase.GetRowColFromAddress(f.Address, out fromRow, out fromCol, out toRow, out toCol); - if (position >= fromRow - && position + (Math.Abs(rows)) - <= toRow) //Insert/delete is whithin the share formula address - { - if (rows - > 0) //Insert - { - f.Address = - ExcelCellBase.GetAddress(fromRow, fromCol) - + ":" - + ExcelCellBase.GetAddress(position - 1, toCol); - if (toRow != fromRow) { - Formulas newF = new Formulas(SourceCodeTokenizer.Default); - newF.StartCol = f.StartCol; - newF.StartRow = position + rows; - newF.Address = - ExcelCellBase.GetAddress(position + rows, fromCol) - + ":" - + ExcelCellBase.GetAddress(toRow + rows, toCol); - newF.Formula = ExcelCellBase.TranslateFromR1C1( - ExcelCellBase.TranslateToR1C1(f.Formula, f.StartRow, f.StartCol), - position, - f.StartCol); - added.Add(newF); - } - } else { - if (fromRow - rows < toRow) { - f.Address = ExcelCellBase.GetAddress(fromRow, fromCol, toRow + rows, toCol); - } else { - f.Address = - ExcelCellBase.GetAddress(fromRow, fromCol) - + ":" - + ExcelCellBase.GetAddress(toRow + rows, toCol); - } - } - } else if (position <= toRow) { - if (rows - > 0) //Insert before shift down - { - f.StartRow += rows; - //f.Formula = ExcelCell.UpdateFormulaReferences(f.Formula, rows, 0, position, 0); //Recalc the cells positions - f.Address = - ExcelCellBase.GetAddress(fromRow + rows, fromCol) - + ":" - + ExcelCellBase.GetAddress(toRow + rows, toCol); - } else { - //Cells[f.Address].SetSharedFormulaID(int.MinValue); - if (position <= fromRow - && position + Math.Abs(rows) - > toRow) //Delete the formula - { - deleted.Add(f); - } else { - toRow = toRow + rows < position - 1 ? position - 1 : toRow + rows; - if (position <= fromRow) { - fromRow = fromRow + rows < position ? position : fromRow + rows; - } - - f.Address = ExcelCellBase.GetAddress(fromRow, fromCol, toRow, toCol); - Cells[f.Address].SetSharedFormulaId(f.Index); - //f.StartRow = fromRow; - - //f.Formula = ExcelCell.UpdateFormulaReferences(f.Formula, rows, 0, position, 0); - } - } - } - } - - AddFormulas(added, position, rows); - - //Remove formulas - foreach (Formulas f in deleted) { - _sharedFormulas.Remove(f.Index); - } - - //Fix Formulas - added = new(); - foreach (int id in _sharedFormulas.Keys) { - var f = _sharedFormulas[id]; - UpdateSharedFormulaRow(ref f, position, rows, ref added); - } - AddFormulas(added, position, rows); - } - - private void AddFormulas(List<Formulas> added, int position, int rows) { - //Add new formulas - foreach (Formulas f in added) { - f.Index = GetMaxShareFunctionIndex(false); - _sharedFormulas.Add(f.Index, f); - Cells[f.Address].SetSharedFormulaId(f.Index); - } - } - - private void UpdateSharedFormulaRow( - ref Formulas formula, - int startRow, - int rows, - ref List<Formulas> newFormulas) { - int fromRow, - fromCol, - toRow, - toCol; - int newFormulasCount = newFormulas.Count; - ExcelCellBase.GetRowColFromAddress( - formula.Address, - out fromRow, - out fromCol, - out toRow, - out toCol); - //int refSplits = Regex.Split(formula.Formula, "#REF!").GetUpperBound(0); - string formualR1C1; - if (rows > 0 || fromRow <= startRow) { - formualR1C1 = ExcelCellBase.TranslateToR1C1( - formula.Formula, - formula.StartRow, - formula.StartCol); - formula.Formula = ExcelCellBase.TranslateFromR1C1(formualR1C1, fromRow, formula.StartCol); - } else { - formualR1C1 = ExcelCellBase.TranslateToR1C1( - formula.Formula, - formula.StartRow - rows, - formula.StartCol); - formula.Formula = ExcelCellBase.TranslateFromR1C1( - formualR1C1, - formula.StartRow, - formula.StartCol); - } - //bool isRef = false; - //Formulas restFormula=formula; - string prevFormualR1C1 = formualR1C1; - for (int row = fromRow; row <= toRow; row++) { - for (int col = fromCol; col <= toCol; col++) { - string newFormula; - string currentFormulaR1C1; - if (rows > 0 || row < startRow) { - newFormula = ExcelCellBase.UpdateFormulaReferences( - ExcelCellBase.TranslateFromR1C1(formualR1C1, row, col), - rows, - 0, - startRow, - 0); - currentFormulaR1C1 = ExcelCellBase.TranslateToR1C1(newFormula, row, col); - } else { - newFormula = ExcelCellBase.UpdateFormulaReferences( - ExcelCellBase.TranslateFromR1C1(formualR1C1, row - rows, col), - rows, - 0, - startRow, - 0); - currentFormulaR1C1 = ExcelCellBase.TranslateToR1C1(newFormula, row, col); - } - if (currentFormulaR1C1 - != prevFormualR1C1) //newFormula.Contains("#REF!")) - { - //if (refSplits == 0 || Regex.Split(newFormula, "#REF!").GetUpperBound(0) != refSplits) - //{ - //isRef = true; - if (row == fromRow && col == fromCol) { - formula.Formula = newFormula; - } else { - if (newFormulas.Count == newFormulasCount) { - formula.Address = ExcelCellBase.GetAddress( - formula.StartRow, - formula.StartCol, - row - 1, - col); - } else { - newFormulas[newFormulas.Count - 1].Address = ExcelCellBase.GetAddress( - newFormulas[newFormulas.Count - 1].StartRow, - newFormulas[newFormulas.Count - 1].StartCol, - row - 1, - col); - } - var refFormula = new Formulas(SourceCodeTokenizer.Default); - refFormula.Formula = newFormula; - refFormula.StartRow = row; - refFormula.StartCol = col; - newFormulas.Add(refFormula); - - //restFormula = null; - prevFormualR1C1 = currentFormulaR1C1; - } - } - // } - // else - // { - // isRef = false; - // } - //} - //else - //{ - // isRef = false; - //} - //if (restFormula==null) - //{ - //if (newFormulas.Count == newFormulasCount) - //{ - // formula.Address = ExcelCellBase.GetAddress(formula.StartRow, formula.StartCol, row - 1, col); - //} - //else - //{ - // newFormulas[newFormulas.Count - 1].Address = ExcelCellBase.GetAddress(newFormulas[newFormulas.Count - 1].StartRow, newFormulas[0].StartCol, row - 1, col); - //} - - //restFormula = new Formulas(); - //restFormula.Formula = newFormula; - //restFormula.StartRow = row; - //restFormula.StartCol = col; - //newFormulas.Add(restFormula); - //} - } - } - if (rows < 0 && formula.StartRow > startRow) { - if (formula.StartRow + rows < startRow) { - formula.StartRow = startRow; - } else { - formula.StartRow += rows; - } - } - if (newFormulas.Count > newFormulasCount) { - newFormulas[newFormulas.Count - 1].Address = ExcelCellBase.GetAddress( - newFormulas[newFormulas.Count - 1].StartRow, - newFormulas[newFormulas.Count - 1].StartCol, - toRow, - toCol); - } - } - /// <summary> /// Delete the specified row from the worksheet. /// </summary> @@ -2409,11 +2143,10 @@ 0, ExcelPackage.MaxColumns); foreach (var column in csec) { - if (column is ExcelColumn) { - var c = (ExcelColumn)column; - if (c._columnMin >= columnFrom) { - c._columnMin -= columns; - c._columnMax -= columns; + if (column is ExcelColumn excelColumn) { + if (excelColumn._columnMin >= columnFrom) { + excelColumn._columnMin -= columns; + excelColumn._columnMax -= columns; } } } @@ -2480,19 +2213,11 @@ delSf.Add(sf.Index); } else { sf.Address = a.Address; - //sf.Formula = ExcelCellBase.UpdateFormulaReferences(sf.Formula, 0, -columns, 0, columnFrom); if (sf.StartCol > columnFrom) { var c = Math.Min(sf.StartCol - columnFrom, columns); sf.Formula = ExcelCellBase.UpdateFormulaReferences(sf.Formula, 0, -c, 0, 1); sf.StartCol -= c; } - - //sf.Address = a.Address; - //sf.Formula = ExcelCellBase.UpdateFormulaReferences(sf.Formula, 0,-columns,0, columnFrom); - //if (sf.StartCol >= columnFrom) - //{ - // sf.StartCol -= sf.StartCol; - //} } } foreach (var ix in delSf) { @@ -2535,10 +2260,8 @@ /// <returns>The value</returns> public object GetValue(int row, int column) { CheckSheetType(); - //ulong cellID = ExcelCellBase.GetCellID(SheetID, Row, Column); var v = _values.GetValue(row, column); if (v != null) { - //var cell = ((ExcelCell)_cells[cellID]); if (_flags.GetFlagValue(row, column, CellFlags.RichText)) { return Cells[row, column].RichText.Text; } @@ -2587,8 +2310,7 @@ return ((T)(object)(new DateTime(((TimeSpan)v).Ticks))); } if (fromType == typeof(string)) { - DateTime dt; - if (DateTime.TryParse(v.ToString(), out dt)) { + if (DateTime.TryParse(v.ToString(), out var dt)) { return (T)(object)(dt); } return default(T); @@ -2605,8 +2327,7 @@ return ((T)(object)(new TimeSpan(((DateTime)v).Ticks))); } if (fromType == typeof(string)) { - TimeSpan ts; - if (TimeSpan.TryParse(v.ToString(), out ts)) { + if (TimeSpan.TryParse(v.ToString(), out var ts)) { return (T)(object)(ts); } return default(T); @@ -2666,9 +2387,7 @@ /// <param name="value">The value</param> public void SetValue(string address, object value) { CheckSheetType(); - int row, - col; - ExcelCellBase.GetRowCol(address, out row, out col, true); + ExcelCellBase.GetRowCol(address, out var row, out var col, true); if (row < 1 || col < 1 || row > ExcelPackage.MaxRows && col > ExcelPackage.MaxColumns) { throw new ArgumentOutOfRangeException("Address is invalid or out of range"); } @@ -2739,18 +2458,13 @@ GetBlockPos(xml, "cols", ref colStart, ref colEnd); streamWriter.Write(xml.Substring(0, colStart)); - var colBreaks = new List<int>(); - //if (_columns.Count > 0) - //{ UpdateColumnData(streamWriter); - //} int cellStart = colEnd, cellEnd = colEnd; GetBlockPos(xml, "sheetData", ref cellStart, ref cellEnd); streamWriter.Write(xml.Substring(colEnd, cellStart - colEnd)); - var rowBreaks = new List<int>(); UpdateRowCellData(streamWriter); int mergeStart = cellEnd, @@ -2768,28 +2482,19 @@ hyperEnd = mergeEnd; GetBlockPos(xml, "hyperlinks", ref hyperStart, ref hyperEnd); streamWriter.Write(xml.Substring(mergeEnd, hyperStart - mergeEnd)); - //if (_hyperLinkCells.Count > 0) - //{ UpdateHyperLinks(streamWriter); - // } int rowBreakStart = hyperEnd, rowBreakEnd = hyperEnd; GetBlockPos(xml, "rowBreaks", ref rowBreakStart, ref rowBreakEnd); streamWriter.Write(xml.Substring(hyperEnd, rowBreakStart - hyperEnd)); - //if (rowBreaks.Count > 0) - //{ UpdateRowBreaks(streamWriter); - //} int colBreakStart = rowBreakEnd, colBreakEnd = rowBreakEnd; GetBlockPos(xml, "colBreaks", ref colBreakStart, ref colBreakEnd); streamWriter.Write(xml.Substring(rowBreakEnd, colBreakStart - rowBreakEnd)); - //if (colBreaks.Count > 0) - //{ UpdateColBreaks(streamWriter); - //} streamWriter.Write(xml.Substring(colBreakEnd, xml.Length - colBreakEnd)); } } @@ -3114,7 +2819,6 @@ StringBuilder breaks = new StringBuilder(); int count = 0; var cse = new CellsStoreEnumerator<object>(_values, 0, 0, 0, ExcelPackage.MaxColumns); - //foreach (ExcelColumn col in _columns) while (cse.Next()) { var col = cse.Value as ExcelColumn; if (col != null && col.PageBreak) { @@ -3148,21 +2852,7 @@ /// Inserts the cols collection into the XML document /// </summary> private void UpdateColumnData(StreamWriter sw) { - //ExcelColumn prevCol = null; //commented out 11/1-12 JK - //foreach (ExcelColumn col in _columns) - //{ - // if (prevCol != null) - // { - // if(prevCol.ColumnMax != col.ColumnMin-1) - // { - // prevCol._columnMax=col.ColumnMin-1; - // } - // } - // prevCol = col; - //} var cse = new CellsStoreEnumerator<object>(_values, 0, 1, 0, ExcelPackage.MaxColumns); - //sw.Write("<cols>"); - //foreach (ExcelColumn col in _columns) bool first = true; while (cse.Next()) { if (first) { @@ -3203,11 +2893,6 @@ sw.Write(" style=\"{0}\"", styleId); } sw.Write(" />"); - - //if (col.PageBreak) - //{ - // colBreaks.Add(col.ColumnMin); - //} } if (!first) { sw.Write("</cols>"); @@ -3258,8 +2943,7 @@ } object v = cse.Value; object formula = _formulas.GetValue(cse.Row, cse.Column); - if (formula is int) { - int sfId = (int)formula; + if (formula is int sfId) { var f = _sharedFormulas[sfId]; if (f.Address.IndexOf(':') > 0) { if (f.StartCol == cse.Column && f.StartRow == cse.Row) { @@ -3366,14 +3050,8 @@ } } } - ////Update hyperlinks. - //if (cell.Hyperlink != null) - //{ - // _hyperLinkCells.Add(cell.CellID); - //} } else //ExcelRow { - //int newRow=((ExcelRow)cse.Value).Row; WriteRow(cache, cellXfs, row, cse.Row); row = cse.Row; } @@ -3392,8 +3070,6 @@ } private object GetFormulaValue(object v) { - //if (_workbook._isCalculated) - //{ if (v != null && v.ToString() != "") { return "<v>" + SecurityElement.Escape(GetValueForXml(v)) + "</v>"; //Fixes issue 15071 } @@ -3404,7 +3080,7 @@ if (v is bool) { return " t=\"b\""; } - if ((v is double && double.IsInfinity((double)v)) || v is ExcelErrorValue) { + if ((v is double d && double.IsInfinity(d)) || v is ExcelErrorValue) { return " t=\"e\""; } if (allowStr @@ -3422,21 +3098,21 @@ private string GetValueForXml(object v) { string s; try { - if (v is DateTime) { - double sdv = ((DateTime)v).ToOADate(); + if (v is DateTime time) { + double sdv = time.ToOADate(); if (Workbook.Date1904) { sdv -= ExcelWorkbook._date1904Offset; } s = sdv.ToString(CultureInfo.InvariantCulture); - } else if (v is TimeSpan) { - s = new DateTime(((TimeSpan)v).Ticks).ToOADate().ToString(CultureInfo.InvariantCulture); + } else if (v is TimeSpan span) { + s = new DateTime(span.Ticks).ToOADate().ToString(CultureInfo.InvariantCulture); ; } else if (v.GetType().IsPrimitive || v is double || v is decimal) { - if (v is double && double.IsNaN((double)v)) { + if (v is double d && double.IsNaN(d)) { s = ""; - } else if (v is double && double.IsInfinity((double)v)) { + } else if (v is double d1 && double.IsInfinity(d1)) { s = "#NUM!"; } else { s = Convert @@ -3494,48 +3170,6 @@ cache.Append(">"); } - private void WriteRow( - StreamWriter sw, - ExcelStyleCollection<ExcelXfs> cellXfs, - int prevRow, - int row) { - if (prevRow != -1) { - sw.Write("</row>"); - } - //ulong rowID = ExcelRow.GetRowID(SheetID, row); - sw.Write("<row r=\"{0}\" ", row); - RowInternal currRow = _values.GetValue(row, 0) as RowInternal; - if (currRow != null) { - if (currRow.Hidden) { - sw.Write("ht=\"0\" hidden=\"1\" "); - } else if (currRow.Height != DefaultRowHeight) { - sw.Write(string.Format(CultureInfo.InvariantCulture, "ht=\"{0}\" ", currRow.Height)); - if (currRow.CustomHeight) { - sw.Write("customHeight=\"1\" "); - } - } - - if (currRow.OutlineLevel > 0) { - sw.Write("outlineLevel =\"{0}\" ", currRow.OutlineLevel); - if (currRow.Collapsed) { - if (currRow.Hidden) { - sw.Write(" collapsed=\"1\" "); - } else { - sw.Write(" collapsed=\"1\" hidden=\"1\" "); //Always hidden - } - } - } - if (currRow.Phonetic) { - sw.Write("ph=\"1\" "); - } - } - var s = _styles.GetValue(row, 0); - if (s > 0) { - sw.Write("s=\"{0}\" customFormat=\"1\"", cellXfs[s].newID); - } - sw.Write(">"); - } - /// <summary> /// Update xml with hyperlinks /// </summary> @@ -3553,26 +3187,24 @@ //int row, col; var uri = _hyperLinks.GetValue(cse.Row, cse.Column); //ExcelCell cell = _cells[cellId] as ExcelCell; - if (uri is ExcelHyperLink - && !string.IsNullOrEmpty((uri as ExcelHyperLink).ReferenceAddress)) { - ExcelHyperLink hl = uri as ExcelHyperLink; + if (uri is ExcelHyperLink link && !string.IsNullOrEmpty(link.ReferenceAddress)) { sw.Write( "<hyperlink ref=\"{0}\" location=\"{1}\" {2}{3}/>", - Cells[cse.Row, cse.Column, cse.Row + hl.RowSpann, cse.Column + hl.ColSpann].Address, + Cells[cse.Row, cse.Column, cse.Row + link.RowSpann, cse.Column + link.ColSpann].Address, ExcelCellBase.GetFullAddress( SecurityElement.Escape(Name), - SecurityElement.Escape(hl.ReferenceAddress)), - string.IsNullOrEmpty(hl.Display) + SecurityElement.Escape(link.ReferenceAddress)), + string.IsNullOrEmpty(link.Display) ? "" - : "display=\"" + SecurityElement.Escape(hl.Display) + "\" ", - string.IsNullOrEmpty(hl.ToolTip) + : "display=\"" + SecurityElement.Escape(link.Display) + "\" ", + string.IsNullOrEmpty(link.ToolTip) ? "" - : "tooltip=\"" + SecurityElement.Escape(hl.ToolTip) + "\" "); + : "tooltip=\"" + SecurityElement.Escape(link.ToolTip) + "\" "); } else if (uri != null) { string id; Uri hyp; - if (uri is ExcelHyperLink) { - hyp = ((ExcelHyperLink)uri).OriginalUri; + if (uri is ExcelHyperLink hyperLink) { + hyp = hyperLink.OriginalUri; } else { hyp = uri; } @@ -3583,8 +3215,7 @@ hyp, TargetMode.External, ExcelPackage._schemaHyperlink); - if (uri is ExcelHyperLink) { - ExcelHyperLink hl = uri as ExcelHyperLink; + if (uri is ExcelHyperLink hl) { sw.Write( "<hyperlink ref=\"{0}\" {2}{3}r:id=\"{1}\" />", ExcelCellBase.GetAddress(cse.Row, cse.Column), @@ -3637,11 +3268,7 @@ public ExcelAddressBase Dimension { get { CheckSheetType(); - int fromRow, - fromCol, - toRow, - toCol; - if (_values.GetDimension(out fromRow, out fromCol, out toRow, out toCol)) { + if (_values.GetDimension(out var fromRow, out var fromCol, out var toRow, out var toCol)) { var addr = new ExcelAddressBase(fromRow, fromCol, toRow, toCol); addr._ws = Name; return addr; @@ -3800,9 +3427,9 @@ var cse = new CellsStoreEnumerator<object>(_values); var offset = Workbook.Date1904 ? -ExcelWorkbook._date1904Offset : ExcelWorkbook._date1904Offset; while (cse.MoveNext()) { - if (cse.Value is DateTime) { + if (cse.Value is DateTime time) { try { - double sdv = ((DateTime)cse.Value).ToOADate(); + double sdv = time.ToOADate(); sdv += offset; cse.Value = DateTime.FromOADate(sdv); @@ -3813,8 +3440,8 @@ public string GetFormula(int row, int col) { var v = _formulas.GetValue(row, col); - if (v is int) { - return _sharedFormulas[(int)v].GetFormula(row, col, Name); + if (v is int i) { + return _sharedFormulas[i].GetFormula(row, col, Name); } if (v != null) { return v.ToString(); @@ -3824,8 +3451,8 @@ public string GetFormulaR1C1(int row, int col) { var v = _formulas.GetValue(row, col); - if (v is int) { - var sf = _sharedFormulas[(int)v]; + if (v is int i) { + var sf = _sharedFormulas[i]; return ExcelCellBase.TranslateToR1C1( Formulas.RemoveDummyFunction(sf.Formula), sf.StartRow, @@ -3839,8 +3466,8 @@ public string GetFormulaR1C1_V1(int row, int col) { var v = _formulas.GetValue(row, col); - if (v is int) { - var sf = _sharedFormulas[(int)v]; + if (v is int i) { + var sf = _sharedFormulas[i]; return ExcelCellBase.TranslateToR1C1_V1( Formulas.RemoveDummyFunction(sf.Formula), sf.StartRow, @@ -3857,8 +3484,8 @@ public string GetArrayFormulaAddress(int row, int col) { var v = _formulas.GetValue(row, col); - if ((v is int) && (_sharedFormulas[(int)v].IsArray)) { - return _sharedFormulas[(int)v].Address; + if ((v is int i) && (_sharedFormulas[i].IsArray)) { + return _sharedFormulas[i].Address; } return ""; }
diff --git a/EPPlus/ExcelWorksheetView.cs b/EPPlus/ExcelWorksheetView.cs index 03303b8..bd132e5 100644 --- a/EPPlus/ExcelWorksheetView.cs +++ b/EPPlus/ExcelWorksheetView.cs
@@ -66,14 +66,17 @@ return address; } set { - int fromCol, - fromRow, - toCol, + int toCol, toRow; if (_selectionNode == null) { CreateSelectionElement(); } - ExcelCellBase.GetRowColFromAddress(value, out fromRow, out fromCol, out toRow, out toCol); + ExcelCellBase.GetRowColFromAddress( + value, + out var fromRow, + out var fromCol, + out toRow, + out toCol); SetXmlNodeString(_activeCellPath, value); if (((XmlElement)TopNode).GetAttribute("sqref") == "") { SelectedRange = ExcelCellBase.GetAddress(fromRow, fromCol); @@ -102,14 +105,17 @@ return address; } set { - int fromCol, - fromRow, - toCol, + int toCol, toRow; if (_selectionNode == null) { CreateSelectionElement(); } - ExcelCellBase.GetRowColFromAddress(value, out fromRow, out fromCol, out toRow, out toCol); + ExcelCellBase.GetRowColFromAddress( + value, + out var fromRow, + out var fromCol, + out toRow, + out toCol); SetXmlNodeString(_selectionRangePath, value); if (((XmlElement)TopNode).GetAttribute("activeCell") == "") { ActiveCell = ExcelCellBase.GetAddress(fromRow, fromCol); @@ -152,44 +158,27 @@ /// </summary> protected internal XmlElement SheetViewElement => (XmlElement)TopNode; - private XmlElement _selectionNode; - - private XmlElement SelectionNode { - get { - _selectionNode = - SheetViewElement.SelectSingleNode("//d:selection", _worksheet.NameSpaceManager) - as XmlElement; - if (_selectionNode == null) { - _selectionNode = _worksheet.WorksheetXml.CreateElement( - "selection", - ExcelPackage._schemaMain); - SheetViewElement.AppendChild(_selectionNode); - } - return _selectionNode; - } - } - /// <summary> /// The active cell. /// </summary> public string ActiveCell { - get { return Panes[Panes.GetUpperBound(0)].ActiveCell; } - set { Panes[Panes.GetUpperBound(0)].ActiveCell = value; } + get => Panes[Panes.GetUpperBound(0)].ActiveCell; + set => Panes[Panes.GetUpperBound(0)].ActiveCell = value; } /// <summary> /// Selected Cells in the worksheet.Used in combination with ActiveCell /// </summary> public string SelectedRange { - get { return Panes[Panes.GetUpperBound(0)].SelectedRange; } - set { Panes[Panes.GetUpperBound(0)].SelectedRange = value; } + get => Panes[Panes.GetUpperBound(0)].SelectedRange; + set => Panes[Panes.GetUpperBound(0)].SelectedRange = value; } /// <summary> /// Indicates if the worksheet is selected within the workbook /// </summary> public bool TabSelected { - get { return GetXmlNodeBool("@tabSelected"); } + get => GetXmlNodeBool("@tabSelected"); set { if (value) { // // ensure no other worksheet has its tabSelected attribute set to 1 @@ -215,7 +204,7 @@ /// Sets the view mode of the worksheet to pagelayout /// </summary> public bool PageLayoutView { - get { return GetXmlNodeString("@view") == "pageLayout"; } + get => GetXmlNodeString("@view") == "pageLayout"; set { if (value) { SetXmlNodeString("@view", "pageLayout"); @@ -229,7 +218,7 @@ /// Sets the view mode of the worksheet to pagebreak /// </summary> public bool PageBreakView { - get { return GetXmlNodeString("@view") == "pageBreakPreview"; } + get => GetXmlNodeString("@view") == "pageBreakPreview"; set { if (value) { SetXmlNodeString("@view", "pageBreakPreview"); @@ -243,23 +232,23 @@ /// Show gridlines in the worksheet /// </summary> public bool ShowGridLines { - get { return GetXmlNodeBool("@showGridLines"); } - set { SetXmlNodeString("@showGridLines", value ? "1" : "0"); } + get => GetXmlNodeBool("@showGridLines"); + set => SetXmlNodeString("@showGridLines", value ? "1" : "0"); } /// <summary> /// Show the Column/Row headers (containg column letters and row numbers) /// </summary> public bool ShowHeaders { - get { return GetXmlNodeBool("@showRowColHeaders"); } - set { SetXmlNodeString("@showRowColHeaders", value ? "1" : "0"); } + get => GetXmlNodeBool("@showRowColHeaders"); + set => SetXmlNodeString("@showRowColHeaders", value ? "1" : "0"); } /// <summary> /// Window zoom magnification for current view representing percent values. /// </summary> public int ZoomScale { - get { return GetXmlNodeInt("@zoomScale"); } + get => GetXmlNodeInt("@zoomScale"); set { if (value < 10 || value > 400) { throw new ArgumentOutOfRangeException("Zoome scale out of range (10-400)"); @@ -272,13 +261,13 @@ /// Flag indicating whether the sheet is in 'right to left' display mode. When in this mode,Column A is on the far right, Column B ;is one column left of Column A, and so on. Also,information in cells is displayed in the Right to Left format. /// </summary> public bool RightToLeft { - get { return GetXmlNodeBool("@rightToLeft"); } - set { SetXmlNodeString("@rightToLeft", value ? "1" : "0"); } + get => GetXmlNodeBool("@rightToLeft"); + set => SetXmlNodeString("@rightToLeft", value ? "1" : "0"); } internal bool WindowProtection { - get { return GetXmlNodeBool("@windowProtection", false); } - set { SetXmlNodeBool("@windowProtection", value, false); } + get => GetXmlNodeBool("@windowProtection", false); + set => SetXmlNodeBool("@windowProtection", value, false); } /// <summary>
diff --git a/EPPlus/ExcelWorksheets.cs b/EPPlus/ExcelWorksheets.cs index dd56dab..1ed69a2 100644 --- a/EPPlus/ExcelWorksheets.cs +++ b/EPPlus/ExcelWorksheets.cs
@@ -338,9 +338,7 @@ /// </summary> /// <param name="name">The name of the worksheet</param> /// <returns></returns> - public ExcelWorksheet this[string name] { - get { return GetByName(name); } - } + public ExcelWorksheet this[string name] => GetByName(name); internal ExcelWorksheet GetBySheetId(int localSheetId) { foreach (ExcelWorksheet ws in this) {
diff --git a/EPPlus/FormulaParsing/CalculateExtentions.cs b/EPPlus/FormulaParsing/CalculateExtentions.cs index 9cb1c28..8d8792b 100644 --- a/EPPlus/FormulaParsing/CalculateExtentions.cs +++ b/EPPlus/FormulaParsing/CalculateExtentions.cs
@@ -75,36 +75,6 @@ CalcChain(worksheet.Workbook, parser, dc); } - // I added this method in December 2019 to analyze why formula calculation was taking - // so long during a 'Regenerate' of a Microsoft Excel table. - private static void DisplayCalcChain(ExcelWorksheet worksheet, DependencyChain dc) { - // Open Output file - string outputFolderName = @"C:\\EPPlus"; - Directory.CreateDirectory(outputFolderName); - DateTime invocationDateTime = DateTime.Now; - string outputFileName = Path.Combine( - outputFolderName, - $"CalcChain_{worksheet.Name}_{invocationDateTime.ToString("yyyyMMdd_HHmmss_fff")}.txt"); - FileStream fileStream = new FileStream(outputFileName, FileMode.CreateNew); - StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8, 65536); - - // Display CalcChain - foreach (int index in dc.CalcOrder) { - FormulaCell formulaCell = dc.list[index]; - string calcChainValue = ""; - calcChainValue += $"Index {index}, "; - calcChainValue += $"Worksheet '{formulaCell.ws.Name}', "; - calcChainValue += $"Row {formulaCell.Row}, "; - calcChainValue += $"Col {formulaCell.Column}, "; - calcChainValue += $" Formula '{formulaCell.Formula}'"; - streamWriter.WriteLine(calcChainValue); - } - - // Close Output file - streamWriter.Flush(); - streamWriter.Close(); - } - public static void Calculate(this ExcelRangeBase range) { Calculate(range, new()); }
diff --git a/EPPlus/FormulaParsing/DependencyChain/DependenyChainFactory.cs b/EPPlus/FormulaParsing/DependencyChain/DependenyChainFactory.cs index 009a8e5..f198123 100644 --- a/EPPlus/FormulaParsing/DependencyChain/DependenyChainFactory.cs +++ b/EPPlus/FormulaParsing/DependencyChain/DependenyChainFactory.cs
@@ -101,16 +101,16 @@ ExcelNamedRange name, ExcelCalculationOption options) { var ws = name.Worksheet; - var id = ExcelCellBase.GetCellId(ws == null ? 0 : ws.SheetID, name.Index, 0); + var id = ExcelCellBase.GetCellId(ws?.SheetID ?? 0, name.Index, 0); if (!depChain.index.ContainsKey(id)) { var f = new FormulaCell { - SheetID = ws == null ? 0 : ws.SheetID, + SheetID = ws?.SheetID ?? 0, Row = name.Index, Column = 0, Formula = name.NameFormula, }; if (!string.IsNullOrEmpty(f.Formula)) { - f.Tokens = lexer.Tokenize(f.Formula, (ws == null ? null : ws.Name)).ToList(); + f.Tokens = lexer.Tokenize(f.Formula, ws?.Name).ToList(); if (ws == null) { name._workbook._formulaTokens.SetValue(name.Index, 0, f.Tokens); } else { @@ -164,8 +164,8 @@ Row = fs.Row, Column = fs.Column, }; - if (fs.Value is int) { - f.Formula = ws._sharedFormulas[(int)fs.Value].GetFormula(fs.Row, fs.Column, ws.Name); + if (fs.Value is int value) { + f.Formula = ws._sharedFormulas[value].GetFormula(fs.Row, fs.Column, ws.Name); } else { f.Formula = fs.Value.ToString(); } @@ -237,15 +237,13 @@ } } } else if (t.TokenType == TokenType.NameValue) { - string adrWb, - adrWs, - adrName; + string adrWb; ExcelNamedRange name; ExcelAddressBase.SplitAddress( t.Value, out adrWb, - out adrWs, - out adrName, + out var adrWs, + out var adrName, f.ws == null ? "" : f.ws.Name); if (!string.IsNullOrEmpty(adrWs)) { if (f.ws == null) {
diff --git a/EPPlus/FormulaParsing/EpplusExcelDataProvider.cs b/EPPlus/FormulaParsing/EpplusExcelDataProvider.cs index 0783dcc..8dfe6d1 100644 --- a/EPPlus/FormulaParsing/EpplusExcelDataProvider.cs +++ b/EPPlus/FormulaParsing/EpplusExcelDataProvider.cs
@@ -68,15 +68,11 @@ public ICellInfo Current => _cell; - public ExcelWorksheet Worksheet { - get { return _ws; } - } + public ExcelWorksheet Worksheet => _ws; public void Dispose() {} - object IEnumerator.Current { - get { return this; } - } + object IEnumerator.Current => this; public bool MoveNext() { _cellCount++; @@ -101,9 +97,7 @@ return this; } - public ExcelAddressBase Address { - get { return _address; } - } + public ExcelAddressBase Address => _address; public object GetValue(int row, int col) { return _ws.GetValue(row, col);
diff --git a/EPPlus/FormulaParsing/Excel/Functions/ArgumentCollectionUtil.cs b/EPPlus/FormulaParsing/Excel/Functions/ArgumentCollectionUtil.cs index 3abd514..9f04f77 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/ArgumentCollectionUtil.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/ArgumentCollectionUtil.cs
@@ -72,8 +72,8 @@ double result, Func<FunctionArgument, double, double> action) { foreach (var item in collection) { - if (item.Value is IEnumerable<FunctionArgument>) { - result = CalculateCollection((IEnumerable<FunctionArgument>)item.Value, result, action); + if (item.Value is IEnumerable<FunctionArgument> value) { + result = CalculateCollection(value, result, action); } else { result = action(item, result); }
diff --git a/EPPlus/FormulaParsing/Excel/Functions/BoolArgumentParser.cs b/EPPlus/FormulaParsing/Excel/Functions/BoolArgumentParser.cs index f492580..3f24d9c 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/BoolArgumentParser.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/BoolArgumentParser.cs
@@ -31,21 +31,20 @@ public class BoolArgumentParser : ArgumentParser { public override object Parse(object obj) { - if (obj is ExcelDataProvider.IRangeInfo) { - var r = ((ExcelDataProvider.IRangeInfo)obj).FirstOrDefault(); - obj = (r == null ? null : r.Value); + if (obj is ExcelDataProvider.IRangeInfo info) { + var r = info.FirstOrDefault(); + obj = r?.Value; } if (obj == null) { return false; } - if (obj is bool) { - return (bool)obj; + if (obj is bool b) { + return b; } if (obj.IsNumeric()) { return Convert.ToBoolean(obj); } - bool result; - if (bool.TryParse(obj.ToString(), out result)) { + if (bool.TryParse(obj.ToString(), out var result)) { return result; } return result;
diff --git a/EPPlus/FormulaParsing/Excel/Functions/CollectionFlattener.cs b/EPPlus/FormulaParsing/Excel/Functions/CollectionFlattener.cs index 04eeab3..dfcf5d9 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/CollectionFlattener.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/CollectionFlattener.cs
@@ -42,8 +42,8 @@ List<T> argList, Action<FunctionArgument, IList<T>> convertFunc) { foreach (var arg in arguments) { - if (arg.Value is IEnumerable<FunctionArgument>) { - FuncArgsToFlatEnumerable((IEnumerable<FunctionArgument>)arg.Value, argList, convertFunc); + if (arg.Value is IEnumerable<FunctionArgument> value) { + FuncArgsToFlatEnumerable(value, argList, convertFunc); } else { convertFunc(arg, argList); }
diff --git a/EPPlus/FormulaParsing/Excel/Functions/DateTime/DateValue.cs b/EPPlus/FormulaParsing/Excel/Functions/DateTime/DateValue.cs index 0b5f372..a474018 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/DateTime/DateValue.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/DateTime/DateValue.cs
@@ -17,8 +17,7 @@ } internal CompileResult Execute(string dateString) { - System.DateTime result; - System.DateTime.TryParse(dateString, out result); + System.DateTime.TryParse(dateString, out var result); return result != System.DateTime.MinValue ? CreateResult(result.ToOADate(), DataType.Date) : CreateResult(ExcelErrorValue.Create(eErrorType.Value), DataType.ExcelError);
diff --git a/EPPlus/FormulaParsing/Excel/Functions/DateTime/Days360.cs b/EPPlus/FormulaParsing/Excel/Functions/DateTime/Days360.cs index 20810ef..797053e 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/DateTime/Days360.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/DateTime/Days360.cs
@@ -68,10 +68,4 @@ - (startYear * 12 * 30 + startMonth * 30 + startDay); return CreateResult(result, DataType.Integer); } - - private int GetNumWholeMonths(System.DateTime dt1, System.DateTime dt2) { - var startDate = new System.DateTime(dt1.Year, dt1.Month, 1).AddMonths(1); - var endDate = new System.DateTime(dt2.Year, dt2.Month, 1); - return ((endDate.Year - startDate.Year) * 12) + (endDate.Month - startDate.Month); - } }
diff --git a/EPPlus/FormulaParsing/Excel/Functions/DateTime/TimeStringParser.cs b/EPPlus/FormulaParsing/Excel/Functions/DateTime/TimeStringParser.cs index 4a76f6f..533528d 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/DateTime/TimeStringParser.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/DateTime/TimeStringParser.cs
@@ -64,8 +64,7 @@ if (Regex.IsMatch(input, _regEx12)) { return Parse12HourTimeString(input); } - System.DateTime dateTime; - if (System.DateTime.TryParse(input, out dateTime)) { + if (System.DateTime.TryParse(input, out var dateTime)) { return GetSerialNumber(dateTime.Hour, dateTime.Minute, dateTime.Second); } return -1; @@ -74,10 +73,7 @@ private double Parse12HourTimeString(string input) { string dayPart = string.Empty; dayPart = input.Substring(input.Length - 2, 2); - int hour; - int minute; - int second; - GetValuesFromString(input, out hour, out minute, out second); + GetValuesFromString(input, out var hour, out var minute, out var second); if (dayPart == "PM") { hour += 12; } @@ -86,10 +82,7 @@ } private double Parse24HourTimeString(string input) { - int hour; - int minute; - int second; - GetValuesFromString(input, out hour, out minute, out second); + GetValuesFromString(input, out var hour, out var minute, out var second); ValidateValues(hour, minute, second); return GetSerialNumber(hour, minute, second); }
diff --git a/EPPlus/FormulaParsing/Excel/Functions/DateTime/TimeValue.cs b/EPPlus/FormulaParsing/Excel/Functions/DateTime/TimeValue.cs index ac259b8..c2de2e0 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/DateTime/TimeValue.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/DateTime/TimeValue.cs
@@ -17,8 +17,7 @@ } internal CompileResult Execute(string dateString) { - System.DateTime result; - System.DateTime.TryParse(dateString, out result); + System.DateTime.TryParse(dateString, out var result); return result != System.DateTime.MinValue ? CreateResult(GetTimeValue(result), DataType.Date) : CreateResult(ExcelErrorValue.Create(eErrorType.Value), DataType.ExcelError);
diff --git a/EPPlus/FormulaParsing/Excel/Functions/DoubleArgumentParser.cs b/EPPlus/FormulaParsing/Excel/Functions/DoubleArgumentParser.cs index d987c85..ed0cec4 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/DoubleArgumentParser.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/DoubleArgumentParser.cs
@@ -27,22 +27,22 @@ using System.Linq; using OfficeOpenXml.FormulaParsing.Exceptions; using OfficeOpenXml.FormulaParsing.Utilities; -using util = OfficeOpenXml.Utils; +using ConvertUtil = OfficeOpenXml.Utils.ConvertUtil; namespace OfficeOpenXml.FormulaParsing.Excel.Functions; public class DoubleArgumentParser : ArgumentParser { public override object Parse(object obj) { Require.That(obj).Named("argument").IsNotNull(); - if (obj is ExcelDataProvider.IRangeInfo) { - var r = ((ExcelDataProvider.IRangeInfo)obj).FirstOrDefault(); - return r == null ? 0 : r.ValueDouble; + if (obj is ExcelDataProvider.IRangeInfo info) { + var r = info.FirstOrDefault(); + return r?.ValueDouble ?? 0; } if (obj is double) { return obj; } if (obj.IsNumeric()) { - return util.ConvertUtil.GetValueDouble(obj); + return ConvertUtil.GetValueDouble(obj); } var str = obj != null ? obj.ToString() : string.Empty; try {
diff --git a/EPPlus/FormulaParsing/Excel/Functions/DoubleEnumerableArgConverter.cs b/EPPlus/FormulaParsing/Excel/Functions/DoubleEnumerableArgConverter.cs index 2ff7a2c..1895872 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/DoubleEnumerableArgConverter.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/DoubleEnumerableArgConverter.cs
@@ -68,8 +68,8 @@ (arg, argList) => { //var cellInfo = arg.Value as EpplusExcelDataProvider.CellInfo; //var value = cellInfo != null ? cellInfo.Value : arg.Value; - if (arg.Value is ExcelDataProvider.IRangeInfo) { - foreach (var cell in (ExcelDataProvider.IRangeInfo)arg.Value) { + if (arg.Value is ExcelDataProvider.IRangeInfo info) { + foreach (var cell in info) { argList.Add(cell.ValueDoubleLogical); } } else {
diff --git a/EPPlus/FormulaParsing/Excel/Functions/ExcelFunction.cs b/EPPlus/FormulaParsing/Excel/Functions/ExcelFunction.cs index ad03cae..a1ae44c 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/ExcelFunction.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/ExcelFunction.cs
@@ -86,7 +86,7 @@ var r = arg.ValueAsRangeInfo; return r.GetValue(r.Address._fromRow, r.Address._fromCol); } - return arg == null ? null : arg.Value; + return arg?.Value; } /// <summary>
diff --git a/EPPlus/FormulaParsing/Excel/Functions/FunctionArgument.cs b/EPPlus/FormulaParsing/Excel/Functions/FunctionArgument.cs index 7dec4b3..baa9da7 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/FunctionArgument.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/FunctionArgument.cs
@@ -44,7 +44,7 @@ public object Value { get; private set; } - public Type Type => Value != null ? Value.GetType() : null; + public Type Type => Value?.GetType(); public bool IsExcelRange => Value != null && Value is ExcelDataProvider.IRangeInfo; @@ -56,8 +56,8 @@ public object ValueFirst { get { - if (Value is ExcelDataProvider.INameInfo) { - Value = ((ExcelDataProvider.INameInfo)Value).Value; + if (Value is ExcelDataProvider.INameInfo info) { + Value = info.Value; } var v = Value as ExcelDataProvider.IRangeInfo; if (v == null) {
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Information/ErrorType.cs b/EPPlus/FormulaParsing/Excel/Functions/Information/ErrorType.cs index 9c565cc..f68f0f9 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Information/ErrorType.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Information/ErrorType.cs
@@ -41,7 +41,6 @@ return CreateResult(ExcelErrorValue.Create(eErrorType.Na), DataType.ExcelError); } var errorType = error.ValueAsExcelErrorValue; - int retValue; switch (errorType.Type) { case eErrorType.Null: return CreateResult(1, DataType.Integer);
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Information/IsBlank.cs b/EPPlus/FormulaParsing/Excel/Functions/Information/IsBlank.cs index e231841..8923a4c 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Information/IsBlank.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Information/IsBlank.cs
@@ -38,9 +38,8 @@ } var result = true; foreach (var arg in arguments) { - if (arg.Value is ExcelDataProvider.IRangeInfo) { - var r = (ExcelDataProvider.IRangeInfo)arg.Value; - if (r.GetValue(r.Address._fromRow, r.Address._fromCol) != null) { + if (arg.Value is ExcelDataProvider.IRangeInfo info) { + if (info.GetValue(info.Address._fromRow, info.Address._fromCol) != null) { result = false; } } else {
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Information/IsErr.cs b/EPPlus/FormulaParsing/Excel/Functions/Information/IsErr.cs index ef90818..d857231 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Information/IsErr.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Information/IsErr.cs
@@ -11,14 +11,13 @@ var result = isError.Execute(arguments, context); if ((bool)result.Result) { var arg = GetFirstValue(arguments); - if (arg is ExcelDataProvider.IRangeInfo) { - var r = (ExcelDataProvider.IRangeInfo)arg; - var e = r.GetValue(r.Address._fromRow, r.Address._fromCol) as ExcelErrorValue; + if (arg is ExcelDataProvider.IRangeInfo info) { + var e = info.GetValue(info.Address._fromRow, info.Address._fromCol) as ExcelErrorValue; if (e != null && e.Type == eErrorType.Na) { return CreateResult(false, DataType.Boolean); } } else { - if (arg is ExcelErrorValue && ((ExcelErrorValue)arg).Type == eErrorType.Na) { + if (arg is ExcelErrorValue value && value.Type == eErrorType.Na) { return CreateResult(false, DataType.Boolean); } }
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Information/IsError.cs b/EPPlus/FormulaParsing/Excel/Functions/Information/IsError.cs index d9802cf..11aaf0b 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Information/IsError.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Information/IsError.cs
@@ -37,10 +37,9 @@ return CreateResult(false, DataType.Boolean); } foreach (var argument in arguments) { - if (argument.Value is ExcelDataProvider.IRangeInfo) { - var r = (ExcelDataProvider.IRangeInfo)argument.Value; + if (argument.Value is ExcelDataProvider.IRangeInfo info) { if (ExcelErrorValue.Values.IsErrorValue( - r.GetValue(r.Address._fromRow, r.Address._fromCol))) { + info.GetValue(info.Address._fromRow, info.Address._fromCol))) { return CreateResult(true, DataType.Boolean); } } else {
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Information/IsNa.cs b/EPPlus/FormulaParsing/Excel/Functions/Information/IsNa.cs index 82adcfe..641ea01 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Information/IsNa.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Information/IsNa.cs
@@ -39,7 +39,7 @@ var v = GetFirstValue(arguments); - if (v is ExcelErrorValue && ((ExcelErrorValue)v).Type == eErrorType.Na) { + if (v is ExcelErrorValue value && value.Type == eErrorType.Na) { return CreateResult(true, DataType.Boolean); } return CreateResult(false, DataType.Boolean);
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Information/N.cs b/EPPlus/FormulaParsing/Excel/Functions/Information/N.cs index 18d6665..cf3d171 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Information/N.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Information/N.cs
@@ -12,8 +12,8 @@ ValidateArguments(arguments, 1); var arg = GetFirstValue(arguments); - if (arg is bool) { - var val = (bool)arg ? 1d : 0d; + if (arg is bool b) { + var val = b ? 1d : 0d; return CreateResult(val, DataType.Decimal); } if (IsNumeric(arg)) {
diff --git a/EPPlus/FormulaParsing/Excel/Functions/IntArgumentParser.cs b/EPPlus/FormulaParsing/Excel/Functions/IntArgumentParser.cs index b510d93..40a5d21 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/IntArgumentParser.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/IntArgumentParser.cs
@@ -33,9 +33,8 @@ public class IntArgumentParser : ArgumentParser { public override object Parse(object obj) { Require.That(obj).Named("argument").IsNotNull(); - int result; - if (obj is ExcelDataProvider.IRangeInfo) { - var r = ((ExcelDataProvider.IRangeInfo)obj).FirstOrDefault(); + if (obj is ExcelDataProvider.IRangeInfo info) { + var r = info.FirstOrDefault(); return r == null ? 0 : Convert.ToInt32(r.ValueDouble); } var objType = obj.GetType(); @@ -45,7 +44,7 @@ if (objType == typeof(double) || objType == typeof(decimal)) { return Convert.ToInt32(obj); } - if (!int.TryParse(obj.ToString(), out result)) { + if (!int.TryParse(obj.ToString(), out var result)) { throw new ExcelErrorValueException(ExcelErrorValue.Create(eErrorType.Value)); } return result;
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Math/Average.cs b/EPPlus/FormulaParsing/Excel/Functions/Math/Average.cs index 159d9de..b154d24 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Math/Average.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Math/Average.cs
@@ -52,8 +52,8 @@ if (ShouldIgnore(arg)) { return; } - if (arg.Value is IEnumerable<FunctionArgument>) { - foreach (var item in (IEnumerable<FunctionArgument>)arg.Value) { + if (arg.Value is IEnumerable<FunctionArgument> value) { + foreach (var item in value) { Calculate(item, context, ref retVal, ref nValues, true); } } else if (arg.IsExcelRange) {
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Math/AverageA.cs b/EPPlus/FormulaParsing/Excel/Functions/Math/AverageA.cs index 00f575f..5cbcdb0 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Math/AverageA.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Math/AverageA.cs
@@ -52,8 +52,8 @@ if (ShouldIgnore(arg)) { return; } - if (arg.Value is IEnumerable<FunctionArgument>) { - foreach (var item in (IEnumerable<FunctionArgument>)arg.Value) { + if (arg.Value is IEnumerable<FunctionArgument> value) { + foreach (var item in value) { Calculate(item, context, ref retVal, ref nValues, true); } } else if (arg.IsExcelRange) { @@ -65,9 +65,9 @@ if (IsNumeric(c.Value)) { nValues++; retVal += c.ValueDouble; - } else if (c.Value is bool) { + } else if (c.Value is bool cValue) { nValues++; - retVal += (bool)c.Value ? 1 : 0; + retVal += cValue ? 1 : 0; } else if (c.Value is string) { nValues++; }
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Math/AverageIf.cs b/EPPlus/FormulaParsing/Excel/Functions/Math/AverageIf.cs index 3b83858..0423f98 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Math/AverageIf.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Math/AverageIf.cs
@@ -125,24 +125,4 @@ } return Divide(retVal, nMatches); } - - private double Calculate(FunctionArgument arg, string expression) { - var retVal = 0d; - if (ShouldIgnore(arg) || !_numericExpressionEvaluator.Evaluate(arg.Value, expression)) { - return retVal; - } - if (IsNumeric(arg.Value)) { - retVal += ConvertUtil.GetValueDouble(arg.Value); - } - //else if (arg.Value is System.DateTime) - //{ - // retVal += Convert.ToDateTime(arg.Value).ToOADate(); - //} - else if (arg.Value is IEnumerable<FunctionArgument>) { - foreach (var item in (IEnumerable<FunctionArgument>)arg.Value) { - retVal += Calculate(item, expression); - } - } - return retVal; - } }
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Math/CountA.cs b/EPPlus/FormulaParsing/Excel/Functions/Math/CountA.cs index 3e7fd3c..a9e3b52 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Math/CountA.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Math/CountA.cs
@@ -51,8 +51,8 @@ nItems++; } } - } else if (item.Value is IEnumerable<FunctionArgument>) { - Calculate((IEnumerable<FunctionArgument>)item.Value, context, ref nItems); + } else if (item.Value is IEnumerable<FunctionArgument> value) { + Calculate(value, context, ref nItems); } else { _CheckForAndHandleExcelError(item, context); if (!ShouldIgnore(item) && ShouldCount(item.Value)) {
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Math/CountIf.cs b/EPPlus/FormulaParsing/Excel/Functions/Math/CountIf.cs index e5e7f14..277058c 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Math/CountIf.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Math/CountIf.cs
@@ -50,8 +50,8 @@ result++; } } - } else if (range.Value is IEnumerable<FunctionArgument>) { - foreach (var arg in (IEnumerable<FunctionArgument>)range.Value) { + } else if (range.Value is IEnumerable<FunctionArgument> value) { + foreach (var arg in value) { if (Evaluate(arg.Value, criteria)) { result++; }
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Math/Rank.cs b/EPPlus/FormulaParsing/Excel/Functions/Math/Rank.cs deleted file mode 100644 index ae71b2c..0000000 --- a/EPPlus/FormulaParsing/Excel/Functions/Math/Rank.cs +++ /dev/null
@@ -1,66 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using OfficeOpenXml.FormulaParsing.ExpressionGraph; - -namespace OfficeOpenXml.FormulaParsing.Excel.Functions.Math { - public class Rank : ExcelFunction { - bool _isAvg; - - public Rank(bool isAvg = false) { - _isAvg = isAvg; - } - - public override CompileResult Execute( - IEnumerable<FunctionArgument> arguments, - ParsingContext context) { - ValidateArguments(arguments, 2); - var number = ArgToDecimal(arguments, 0); - var refer = arguments.ElementAt(1); - bool asc = false; - if (arguments.Count() > 2) { - asc = base.ArgToBool(arguments, 2); - } - var l = new List<double>(); - - foreach (var c in refer.ValueAsRangeInfo) { - var v = Utils.ConvertUtil.GetValueDouble(c.Value, false, true); - if (!double.IsNaN(v)) { - l.Add(v); - } - } - l.Sort(); - double ix; - if (asc) { - ix = l.IndexOf(number) + 1; - if (_isAvg) { - int st = Convert.ToInt32(ix); - while (l.Count > st && l[st] == number) { - st++; - } - if (st > ix) { - ix = ix + ((st - ix) / 2D); - } - } - } else { - ix = l.LastIndexOf(number); - if (_isAvg) { - int st = Convert.ToInt32(ix) - 1; - while (0 <= st && l[st] == number) { - st--; - } - if (st + 1 < ix) { - ix = ix - ((ix - st - 1) / 2D); - } - } - ix = l.Count - ix; - } - if (ix <= 0 || ix > l.Count) { - return new CompileResult(ExcelErrorValue.Create(eErrorType.NA), DataType.ExcelError); - } else { - return CreateResult(ix, DataType.Decimal); - } - } - } -}
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Math/Sum.cs b/EPPlus/FormulaParsing/Excel/Functions/Math/Sum.cs index 5d3550e..b9b6850 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Math/Sum.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Math/Sum.cs
@@ -47,12 +47,12 @@ if (ShouldIgnore(arg)) { return retVal; } - if (arg.Value is IEnumerable<FunctionArgument>) { - foreach (var item in (IEnumerable<FunctionArgument>)arg.Value) { + if (arg.Value is IEnumerable<FunctionArgument> value) { + foreach (var item in value) { retVal += Calculate(item, context); } - } else if (arg.Value is ExcelDataProvider.IRangeInfo) { - foreach (var c in (ExcelDataProvider.IRangeInfo)arg.Value) { + } else if (arg.Value is ExcelDataProvider.IRangeInfo info) { + foreach (var c in info) { if (ShouldIgnore(c, context) == false) { CheckForAndHandleExcelError(c); retVal += c.ValueDouble;
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Math/SumIf.cs b/EPPlus/FormulaParsing/Excel/Functions/Math/SumIf.cs index 1750c4e..232d460 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Math/SumIf.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Math/SumIf.cs
@@ -71,23 +71,6 @@ } private double CalculateWithSumRange( - IEnumerable<FunctionArgument> range, - string criteria, - IEnumerable<FunctionArgument> sumRange, - ParsingContext context) { - var retVal = 0d; - var flattenedRange = ArgsToDoubleEnumerable(range, context); - var flattenedSumRange = ArgsToDoubleEnumerable(sumRange, context); - for (var x = 0; x < flattenedRange.Count(); x++) { - var candidate = flattenedSumRange.ElementAt(x); - if (_evaluator.Evaluate(flattenedRange.ElementAt(x), criteria)) { - retVal += candidate; - } - } - return retVal; - } - - private double CalculateWithSumRange( ExcelDataProvider.IRangeInfo range, string criteria, ExcelDataProvider.IRangeInfo sumRange, @@ -100,8 +83,8 @@ if (sumRange.Address._fromRow + or <= sumRange.Address._toRow && sumRange.Address._fromCol + oc <= sumRange.Address._toCol) { var v = sumRange.GetOffset(or, oc); - if (v is ExcelErrorValue) { - throw (new ExcelErrorValueException((ExcelErrorValue)v)); + if (v is ExcelErrorValue value) { + throw (new ExcelErrorValueException(value)); } retVal += Util.ConvertUtil.GetValueDouble(v, true); }
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Math/SumProduct.cs b/EPPlus/FormulaParsing/Excel/Functions/Math/SumProduct.cs index 6985eb7..0ee2d19 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Math/SumProduct.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Math/SumProduct.cs
@@ -41,8 +41,8 @@ foreach (var arg in arguments) { results.Add(new()); var currentResult = results.Last(); - if (arg.Value is IEnumerable<FunctionArgument>) { - foreach (var val in (IEnumerable<FunctionArgument>)arg.Value) { + if (arg.Value is IEnumerable<FunctionArgument> value) { + foreach (var val in value) { AddValue(val.Value, currentResult); } } else if (arg.Value is FunctionArgument) { @@ -77,8 +77,8 @@ private void AddValue(object convertVal, List<double> currentResult) { if (IsNumeric(convertVal)) { currentResult.Add(Convert.ToDouble(convertVal)); - } else if (convertVal is ExcelErrorValue) { - throw (new ExcelErrorValueException((ExcelErrorValue)convertVal)); + } else if (convertVal is ExcelErrorValue val) { + throw (new ExcelErrorValueException(val)); } else { currentResult.Add(0d); }
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Math/Sumsq.cs b/EPPlus/FormulaParsing/Excel/Functions/Math/Sumsq.cs index 9bb56d3..cb18398 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Math/Sumsq.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Math/Sumsq.cs
@@ -22,8 +22,8 @@ if (ShouldIgnore(arg)) { return retVal; } - if (arg.Value is IEnumerable<FunctionArgument>) { - foreach (var item in (IEnumerable<FunctionArgument>)arg.Value) { + if (arg.Value is IEnumerable<FunctionArgument> arguments) { + foreach (var item in arguments) { retVal += Calculate(item, context, true); } } else {
diff --git a/EPPlus/FormulaParsing/Excel/Functions/ObjectEnumerableArgConverter.cs b/EPPlus/FormulaParsing/Excel/Functions/ObjectEnumerableArgConverter.cs index 71c5252..6e56c59 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/ObjectEnumerableArgConverter.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/ObjectEnumerableArgConverter.cs
@@ -35,8 +35,8 @@ return base.FuncArgsToFlatEnumerable( arguments, (arg, argList) => { - if (arg.Value is ExcelDataProvider.IRangeInfo) { - foreach (var cell in (ExcelDataProvider.IRangeInfo)arg.Value) { + if (arg.Value is ExcelDataProvider.IRangeInfo info) { + foreach (var cell in info) { if (!CellStateHelper.ShouldIgnore(ignoreHidden, cell, context)) { argList.Add(cell.Value); }
diff --git a/EPPlus/FormulaParsing/Excel/Functions/RefAndLookup/Address.cs b/EPPlus/FormulaParsing/Excel/Functions/RefAndLookup/Address.cs index 3d75525..b0ce169 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/RefAndLookup/Address.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/RefAndLookup/Address.cs
@@ -48,7 +48,7 @@ } if (arguments.Count() > 3) { var fourthArg = arguments.ElementAt(3).Value; - if (fourthArg is bool && !(bool)fourthArg) { + if (fourthArg is bool arg && !arg) { throw new InvalidOperationException("Excelformulaparser does not support the R1C1 format!"); } }
diff --git a/EPPlus/FormulaParsing/Excel/Functions/Text/Value.cs b/EPPlus/FormulaParsing/Excel/Functions/Text/Value.cs index 3ad4fc8..2a05519 100644 --- a/EPPlus/FormulaParsing/Excel/Functions/Text/Value.cs +++ b/EPPlus/FormulaParsing/Excel/Functions/Text/Value.cs
@@ -16,10 +16,6 @@ .NumberFormat .NumberDecimalSeparator; private readonly string _timeSeparator = CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator; - private readonly string _shortTimePattern = CultureInfo - .CurrentCulture - .DateTimeFormat - .ShortTimePattern; private readonly DateValue _dateValueFunc = new(); private readonly TimeValue _timeValueFunc = new();
diff --git a/EPPlus/FormulaParsing/Excel/Operators/Operator.cs b/EPPlus/FormulaParsing/Excel/Operators/Operator.cs index 9134b3c..e6d25e2 100644 --- a/EPPlus/FormulaParsing/Excel/Operators/Operator.cs +++ b/EPPlus/FormulaParsing/Excel/Operators/Operator.cs
@@ -39,14 +39,10 @@ private const int _precedencePercent = 2; private const int _precedenceExp = 4; private const int _precedenceMultiplyDevide = 6; - private const int _precedenceIntegerDivision = 8; - private const int _precedenceModulus = 10; private const int _precedenceAddSubtract = 12; private const int _precedenceConcat = 15; private const int _precedenceComparison = 25; - private Operator() {} - private Operator( Operators @operator, int precedence, @@ -62,9 +58,7 @@ int IOperator.Precedence => _precedence; - Operators IOperator.Operator { - get { return _operator; } - } + Operators IOperator.Operator => _operator; public CompileResult Apply(CompileResult left, CompileResult right) { if (left.Result is ExcelErrorValue) { @@ -93,8 +87,7 @@ (l, r) => { l = l == null || l.Result == null ? new(0, DataType.Integer) : l; r = r == null || r.Result == null ? new(0, DataType.Integer) : r; - ExcelErrorValue errorVal; - if (EitherIsError(l, r, out errorVal)) { + if (EitherIsError(l, r, out var errorVal)) { return new(errorVal); } if (l.DataType == DataType.Integer && r.DataType == DataType.Integer) { @@ -352,8 +345,7 @@ CompileResult l, CompileResult r, Func<int, bool> comparison) { - ExcelErrorValue errorVal; - if (EitherIsError(l, r, out errorVal)) { + if (EitherIsError(l, r, out var errorVal)) { return new(errorVal); } object left,
diff --git a/EPPlus/FormulaParsing/ExcelCell.cs b/EPPlus/FormulaParsing/ExcelCell.cs deleted file mode 100644 index aedd49c..0000000 --- a/EPPlus/FormulaParsing/ExcelCell.cs +++ /dev/null
@@ -1,18 +0,0 @@ -namespace OfficeOpenXml.FormulaParsing; - -public class ExcelCell { - public ExcelCell(object val, string formula, int colIndex, int rowIndex) { - Value = val; - Formula = formula; - ColIndex = colIndex; - RowIndex = rowIndex; - } - - public int ColIndex { get; private set; } - - public int RowIndex { get; private set; } - - public object Value { get; private set; } - - public string Formula { get; private set; } -}
diff --git a/EPPlus/FormulaParsing/ExcelUtilities/ExpressionEvaluator.cs b/EPPlus/FormulaParsing/ExcelUtilities/ExpressionEvaluator.cs index 53cf288..df05bb4 100644 --- a/EPPlus/FormulaParsing/ExcelUtilities/ExpressionEvaluator.cs +++ b/EPPlus/FormulaParsing/ExcelUtilities/ExpressionEvaluator.cs
@@ -77,8 +77,8 @@ d = Convert.ToDouble(op); return true; } - if (op is DateTime) { - d = ((DateTime)op).ToOADate(); + if (op is DateTime time) { + d = time.ToOADate(); return true; } if (op != null) { @@ -96,8 +96,7 @@ } var operatorCandidate = GetNonAlphanumericStartChars(expression); if (!string.IsNullOrEmpty(operatorCandidate) && operatorCandidate != "-") { - IOperator op; - if (OperatorsDict.Instance.TryGetValue(operatorCandidate, out op)) { + if (OperatorsDict.Instance.TryGetValue(operatorCandidate, out var op)) { var right = expression.Replace(operatorCandidate, string.Empty); if (left == null && right == string.Empty) { return op.Operator == Operators.Equals; @@ -105,12 +104,9 @@ if (left == null ^ right == string.Empty) { return op.Operator == Operators.NotEqualTo; } - double leftNum, - rightNum; - DateTime date; - bool leftIsNumeric = TryConvertToDouble(left, out leftNum); - bool rightIsNumeric = double.TryParse(right, out rightNum); - bool rightIsDate = DateTime.TryParse(right, out date); + bool leftIsNumeric = TryConvertToDouble(left, out var leftNum); + bool rightIsNumeric = double.TryParse(right, out var rightNum); + bool rightIsDate = DateTime.TryParse(right, out var date); if (leftIsNumeric && rightIsNumeric) { return EvaluateOperator(leftNum, rightNum, op); }
diff --git a/EPPlus/FormulaParsing/ExcelUtilities/NumericExpressionEvaluator.cs b/EPPlus/FormulaParsing/ExcelUtilities/NumericExpressionEvaluator.cs index 6e326a7..174d595 100644 --- a/EPPlus/FormulaParsing/ExcelUtilities/NumericExpressionEvaluator.cs +++ b/EPPlus/FormulaParsing/ExcelUtilities/NumericExpressionEvaluator.cs
@@ -67,8 +67,7 @@ return Convert.ToDouble(op); } if (op != null) { - double output; - if (double.TryParse(op.ToString(), out output)) { + if (double.TryParse(op.ToString(), out var output)) { return output; } } @@ -79,11 +78,9 @@ var operatorCandidate = GetNonNumericStartChars(expression); var leftNum = OperandAsDouble(left); if (!string.IsNullOrEmpty(operatorCandidate) && leftNum != null) { - IOperator op; - if (OperatorsDict.Instance.TryGetValue(operatorCandidate, out op)) { + if (OperatorsDict.Instance.TryGetValue(operatorCandidate, out var op)) { var numericCandidate = expression.Replace(operatorCandidate, string.Empty); - double d; - if (double.TryParse(numericCandidate, out d)) { + if (double.TryParse(numericCandidate, out var d)) { var leftResult = _compileResultFactory.Create(leftNum); var rightResult = _compileResultFactory.Create(d); var result = op.Apply(leftResult, rightResult);
diff --git a/EPPlus/FormulaParsing/ExcelUtilities/RangeAddressFactory.cs b/EPPlus/FormulaParsing/ExcelUtilities/RangeAddressFactory.cs index a2ae075..2ff911b 100644 --- a/EPPlus/FormulaParsing/ExcelUtilities/RangeAddressFactory.cs +++ b/EPPlus/FormulaParsing/ExcelUtilities/RangeAddressFactory.cs
@@ -35,7 +35,6 @@ public class RangeAddressFactory { private readonly ExcelDataProvider _excelDataProvider; - private readonly AddressTranslator _addressTranslator; private readonly IndexToAddressTranslator _indexToAddressTranslator; public RangeAddressFactory(ExcelDataProvider excelDataProvider) @@ -52,7 +51,6 @@ Require.That(addressTranslator).Named("addressTranslator").IsNotNull(); Require.That(indexToAddressTranslator).Named("indexToAddressTranslator").IsNotNull(); _excelDataProvider = excelDataProvider; - _addressTranslator = addressTranslator; _indexToAddressTranslator = indexToAddressTranslator; } @@ -91,15 +89,6 @@ ToRow = (dim != null && adr._toRow > dim.Row) ? dim.Row : adr._toRow, ToCol = adr._toCol, }; - - //if (addressInfo.IsMultipleCells) - //{ - // HandleMultipleCellAddress(rangeAddress, addressInfo); - //} - //else - //{ - // HandleSingleCellAddress(rangeAddress, addressInfo); - //} return rangeAddress; } @@ -115,42 +104,6 @@ ToRow = adr._toRow, ToCol = adr._toCol, }; - - //if (addressInfo.IsMultipleCells) - //{ - // HandleMultipleCellAddress(rangeAddress, addressInfo); - //} - //else - //{ - // HandleSingleCellAddress(rangeAddress, addressInfo); - //} return rangeAddress; } - - private void HandleSingleCellAddress(RangeAddress rangeAddress, ExcelAddressInfo addressInfo) { - int col, - row; - _addressTranslator.ToColAndRow(addressInfo.StartCell, out col, out row); - rangeAddress.FromCol = col; - rangeAddress.ToCol = col; - rangeAddress.FromRow = row; - rangeAddress.ToRow = row; - } - - private void HandleMultipleCellAddress(RangeAddress rangeAddress, ExcelAddressInfo addressInfo) { - int fromCol, - fromRow; - _addressTranslator.ToColAndRow(addressInfo.StartCell, out fromCol, out fromRow); - int toCol, - toRow; - _addressTranslator.ToColAndRow( - addressInfo.EndCell, - out toCol, - out toRow, - AddressTranslator.RangeCalculationBehaviour.LastPart); - rangeAddress.FromCol = fromCol; - rangeAddress.ToCol = toCol; - rangeAddress.FromRow = fromRow; - rangeAddress.ToRow = toRow; - } }
diff --git a/EPPlus/FormulaParsing/ExcelUtilities/ValueMatcher.cs b/EPPlus/FormulaParsing/ExcelUtilities/ValueMatcher.cs index aeb4a47..0fb50ba 100644 --- a/EPPlus/FormulaParsing/ExcelUtilities/ValueMatcher.cs +++ b/EPPlus/FormulaParsing/ExcelUtilities/ValueMatcher.cs
@@ -63,15 +63,13 @@ } private static object CheckGetRange(object v) { - if (v is ExcelDataProvider.IRangeInfo) { - var r = ((ExcelDataProvider.IRangeInfo)v); - if (r.GetNCells() > 1) { + if (v is ExcelDataProvider.IRangeInfo info) { + if (info.GetNCells() > 1) { v = ExcelErrorValue.Create(eErrorType.Na); } - v = r.GetOffset(0, 0); - } else if (v is ExcelDataProvider.INameInfo) { - var n = ((ExcelDataProvider.INameInfo)v); - v = CheckGetRange(n); + v = info.GetOffset(0, 0); + } else if (v is ExcelDataProvider.INameInfo nameInfo) { + v = CheckGetRange(nameInfo); } return v; } @@ -81,16 +79,14 @@ } protected virtual int CompareStringToObject(string o1, object o2) { - double d1; - if (double.TryParse(o1, out d1)) { + if (double.TryParse(o1, out var d1)) { return d1.CompareTo(Convert.ToDouble(o2)); } return IncompatibleOperands; } protected virtual int CompareObjectToString(object o1, string o2) { - double d2; - if (double.TryParse(o2, out d2)) { + if (double.TryParse(o2, out var d2)) { return Convert.ToDouble(o1).CompareTo(d2); } return IncompatibleOperands;
diff --git a/EPPlus/FormulaParsing/ExcelValues.cs b/EPPlus/FormulaParsing/ExcelValues.cs index e4d860b..c15c606 100644 --- a/EPPlus/FormulaParsing/ExcelValues.cs +++ b/EPPlus/FormulaParsing/ExcelValues.cs
@@ -198,9 +198,9 @@ } public override bool Equals(object obj) { - if (!(obj is ExcelErrorValue)) { + if (!(obj is ExcelErrorValue value)) { return false; } - return ((ExcelErrorValue)obj).ToString() == ToString(); + return value.ToString() == ToString(); } }
diff --git a/EPPlus/FormulaParsing/Exceptions/ExcelErrorCodes.cs b/EPPlus/FormulaParsing/Exceptions/ExcelErrorCodes.cs index f182e8a..9dc8ea4 100644 --- a/EPPlus/FormulaParsing/Exceptions/ExcelErrorCodes.cs +++ b/EPPlus/FormulaParsing/Exceptions/ExcelErrorCodes.cs
@@ -46,8 +46,8 @@ } public override bool Equals(object obj) { - if (obj is ExcelErrorCodes) { - return ((ExcelErrorCodes)obj).Code.Equals(Code); + if (obj is ExcelErrorCodes codes) { + return codes.Code.Equals(Code); } return false; }
diff --git a/EPPlus/FormulaParsing/ExpressionGraph/CompileResult.cs b/EPPlus/FormulaParsing/ExpressionGraph/CompileResult.cs index 9535d05..2545f6a 100644 --- a/EPPlus/FormulaParsing/ExpressionGraph/CompileResult.cs +++ b/EPPlus/FormulaParsing/ExpressionGraph/CompileResult.cs
@@ -74,11 +74,11 @@ if (IsNumeric) { return Result == null ? 0 : Convert.ToDouble(Result); } - if (Result is DateTime) { - return ((DateTime)Result).ToOADate(); + if (Result is DateTime time) { + return time.ToOADate(); } - if (Result is TimeSpan) { - return new DateTime(((TimeSpan)Result).Ticks).ToOADate(); + if (Result is TimeSpan span) { + return new DateTime(span.Ticks).ToOADate(); } if (IsNumericString) { try { @@ -87,8 +87,8 @@ return 0; } } - if (Result is ExcelDataProvider.IRangeInfo) { - var c = ((ExcelDataProvider.IRangeInfo)Result).FirstOrDefault(); + if (Result is ExcelDataProvider.IRangeInfo info) { + var c = info.FirstOrDefault(); if (c == null) { return 0; } @@ -100,15 +100,12 @@ public DataType DataType { get; private set; } - public bool IsNumeric { - get { - return DataType == DataType.Decimal - || DataType == DataType.Integer - || DataType == DataType.Empty - || DataType == DataType.Boolean - || DataType == DataType.Date; - } - } + public bool IsNumeric => + DataType == DataType.Decimal + || DataType == DataType.Integer + || DataType == DataType.Empty + || DataType == DataType.Boolean + || DataType == DataType.Date; public bool IsNumericString { get { return DataType == DataType.String && ConvertUtil.IsNumericString(Result); }
diff --git a/EPPlus/FormulaParsing/ExpressionGraph/CompileResultFactory.cs b/EPPlus/FormulaParsing/ExpressionGraph/CompileResultFactory.cs index af6f09f..4434031 100644 --- a/EPPlus/FormulaParsing/ExpressionGraph/CompileResultFactory.cs +++ b/EPPlus/FormulaParsing/ExpressionGraph/CompileResultFactory.cs
@@ -35,11 +35,11 @@ public class CompileResultFactory { public virtual CompileResult Create(object obj) { - if ((obj is ExcelDataProvider.INameInfo)) { - obj = ((ExcelDataProvider.INameInfo)obj).Value; + if ((obj is ExcelDataProvider.INameInfo info)) { + obj = info.Value; } - if (obj is ExcelDataProvider.IRangeInfo) { - obj = ((ExcelDataProvider.IRangeInfo)obj).GetOffset(0, 0); + if (obj is ExcelDataProvider.IRangeInfo rangeInfo) { + obj = rangeInfo.GetOffset(0, 0); } if (obj == null) { return new(null, DataType.Empty);
diff --git a/EPPlus/FormulaParsing/ExpressionGraph/DecimalExpression.cs b/EPPlus/FormulaParsing/ExpressionGraph/DecimalExpression.cs index 9c32645..9d82c5a 100644 --- a/EPPlus/FormulaParsing/ExpressionGraph/DecimalExpression.cs +++ b/EPPlus/FormulaParsing/ExpressionGraph/DecimalExpression.cs
@@ -51,9 +51,7 @@ } public override CompileResult Compile() { - double result = _compiledValue.HasValue - ? _compiledValue.Value - : double.Parse(ExpressionString, CultureInfo.InvariantCulture); + double result = _compiledValue ?? double.Parse(ExpressionString, CultureInfo.InvariantCulture); result = _negate ? result * -1 : result; return new(result, DataType.Decimal); }
diff --git a/EPPlus/FormulaParsing/ExpressionGraph/ExcelAddressExpression.cs b/EPPlus/FormulaParsing/ExpressionGraph/ExcelAddressExpression.cs index 4f68d2c..8e409b7 100644 --- a/EPPlus/FormulaParsing/ExpressionGraph/ExcelAddressExpression.cs +++ b/EPPlus/FormulaParsing/ExpressionGraph/ExcelAddressExpression.cs
@@ -107,7 +107,5 @@ return compileResult; } - public bool IsNegated { - get { return _negate; } - } + public bool IsNegated => _negate; }
diff --git a/EPPlus/FormulaParsing/ExpressionGraph/ExpressionGraphBuilder.cs b/EPPlus/FormulaParsing/ExpressionGraph/ExpressionGraphBuilder.cs index de2f384..156b425 100644 --- a/EPPlus/FormulaParsing/ExpressionGraph/ExpressionGraphBuilder.cs +++ b/EPPlus/FormulaParsing/ExpressionGraph/ExpressionGraphBuilder.cs
@@ -65,9 +65,8 @@ private void BuildUp(Token[] tokens, Expression parent) { while (_tokenIndex < tokens.Length) { var token = tokens[_tokenIndex]; - IOperator op = null; if (token.TokenType == TokenType.Operator - && OperatorsDict.Instance.TryGetValue(token.Value, out op)) { + && OperatorsDict.Instance.TryGetValue(token.Value, out var op)) { SetOperatorOnExpression(parent, op); } else if (token.TokenType == TokenType.Function) { BuildFunctionExpression(tokens, parent, token.Value);
diff --git a/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/ErrorHandlingFunctionCompiler.cs b/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/ErrorHandlingFunctionCompiler.cs index 303821a..f93b6ce 100644 --- a/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/ErrorHandlingFunctionCompiler.cs +++ b/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/ErrorHandlingFunctionCompiler.cs
@@ -45,7 +45,7 @@ foreach (var child in children) { try { var arg = child.Compile(); - BuildFunctionArguments(arg != null ? arg.Result : null, args); + BuildFunctionArguments(arg?.Result, args); } catch (ExcelErrorValueException efe) { return ((ErrorHandlingFunction)Function).HandleError(efe.ErrorValue.ToString()); } catch // (Exception e)
diff --git a/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/FunctionCompiler.cs b/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/FunctionCompiler.cs index cb164b0..8be6020 100644 --- a/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/FunctionCompiler.cs +++ b/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/FunctionCompiler.cs
@@ -44,9 +44,8 @@ } protected void BuildFunctionArguments(object result, List<FunctionArgument> args) { - if (result is IEnumerable<object> && !(result is ExcelDataProvider.IRangeInfo)) { + if (result is IEnumerable<object> objects && !(objects is ExcelDataProvider.IRangeInfo)) { var argList = new List<FunctionArgument>(); - var objects = result as IEnumerable<object>; foreach (var arg in objects) { BuildFunctionArguments(arg, argList); }
diff --git a/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/IfFunctionCompiler.cs b/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/IfFunctionCompiler.cs index 0818ce5..15d262b 100644 --- a/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/IfFunctionCompiler.cs +++ b/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/IfFunctionCompiler.cs
@@ -66,20 +66,19 @@ var v = firstChild.Compile().Result; /**** Handle names and ranges ****/ - if (v is ExcelDataProvider.INameInfo) { - v = ((ExcelDataProvider.INameInfo)v).Value; + if (v is ExcelDataProvider.INameInfo info) { + v = info.Value; } - if (v is ExcelDataProvider.IRangeInfo) { - var r = ((ExcelDataProvider.IRangeInfo)v); - if (r.GetNCells() > 1) { + if (v is ExcelDataProvider.IRangeInfo rangeInfo) { + if (rangeInfo.GetNCells() > 1) { throw (new ArgumentException("Logical can't be more than one cell")); } - v = r.GetOffset(0, 0); + v = rangeInfo.GetOffset(0, 0); } bool boolVal; - if (v is bool) { - boolVal = (bool)v; + if (v is bool b) { + boolVal = b; } else { if (ConvertUtil.IsNumeric(v)) { boolVal = ConvertUtil.GetValueDouble(v) != 0;
diff --git a/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/LookupFunctionCompiler.cs b/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/LookupFunctionCompiler.cs index a350504..de672c1 100644 --- a/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/LookupFunctionCompiler.cs +++ b/EPPlus/FormulaParsing/ExpressionGraph/FunctionCompilers/LookupFunctionCompiler.cs
@@ -49,7 +49,7 @@ firstChild = false; } var arg = child.Compile(); - BuildFunctionArguments(arg != null ? arg.Result : null, args); + BuildFunctionArguments(arg?.Result, args); } return Function.Execute(args, context); }
diff --git a/EPPlus/FormulaParsing/ExpressionGraph/IntegerExpression.cs b/EPPlus/FormulaParsing/ExpressionGraph/IntegerExpression.cs index 973b523..f24afa0 100644 --- a/EPPlus/FormulaParsing/ExpressionGraph/IntegerExpression.cs +++ b/EPPlus/FormulaParsing/ExpressionGraph/IntegerExpression.cs
@@ -52,9 +52,7 @@ } public override CompileResult Compile() { - double result = _compiledValue.HasValue - ? _compiledValue.Value - : double.Parse(ExpressionString, CultureInfo.InvariantCulture); + double result = _compiledValue ?? double.Parse(ExpressionString, CultureInfo.InvariantCulture); result = _negate ? result * -1 : result; return new(result, DataType.Integer); }
diff --git a/EPPlus/FormulaParsing/ExpressionGraph/NamedValueExpression.cs b/EPPlus/FormulaParsing/ExpressionGraph/NamedValueExpression.cs index 080f8a0..cdf7582 100644 --- a/EPPlus/FormulaParsing/ExpressionGraph/NamedValueExpression.cs +++ b/EPPlus/FormulaParsing/ExpressionGraph/NamedValueExpression.cs
@@ -53,10 +53,9 @@ if (name.Value == null) { return null; } - if (name.Value is ExcelDataProvider.IRangeInfo) { - var range = (ExcelDataProvider.IRangeInfo)name.Value; + if (name.Value is ExcelDataProvider.IRangeInfo range) { if (range.IsMulti) { - return new(name.Value, DataType.Enumerable); + return new(range, DataType.Enumerable); } if (range.IsEmpty) { return null;
diff --git a/EPPlus/FormulaParsing/FormulaParser.cs b/EPPlus/FormulaParsing/FormulaParser.cs index faa0536..06bd4a6 100644 --- a/EPPlus/FormulaParsing/FormulaParser.cs +++ b/EPPlus/FormulaParsing/FormulaParser.cs
@@ -80,9 +80,8 @@ public ILexer Lexer => _lexer; - public IEnumerable<string> FunctionNames { - get { return _parsingContext.Configuration.FunctionRepository.FunctionNames; } - } + public IEnumerable<string> FunctionNames => + _parsingContext.Configuration.FunctionRepository.FunctionNames; internal virtual object Parse(string formula, RangeAddress rangeAddress) { using (var scope = _parsingContext.Scopes.NewScope(rangeAddress)) {
diff --git a/EPPlus/FormulaParsing/LexicalAnalysis/SourceCodeTokenizer.cs b/EPPlus/FormulaParsing/LexicalAnalysis/SourceCodeTokenizer.cs index 01e9bf9..51f6f4b 100644 --- a/EPPlus/FormulaParsing/LexicalAnalysis/SourceCodeTokenizer.cs +++ b/EPPlus/FormulaParsing/LexicalAnalysis/SourceCodeTokenizer.cs
@@ -71,8 +71,7 @@ bool isSingleQuoteString = false; for (int i = 0; i < context.FormulaChars.Length; i++) { var c = context.FormulaChars[i]; - Token tokenSeparator; - if (CharIsTokenSeparator(c, out tokenSeparator)) { + if (CharIsTokenSeparator(c, out var tokenSeparator)) { if (context.IsInString) { if (IsDoubleQuote(tokenSeparator, i, context)) { i++;
diff --git a/EPPlus/FormulaParsing/LexicalAnalysis/TokenFactory.cs b/EPPlus/FormulaParsing/LexicalAnalysis/TokenFactory.cs index 96c87a3..6ba0d9b 100644 --- a/EPPlus/FormulaParsing/LexicalAnalysis/TokenFactory.cs +++ b/EPPlus/FormulaParsing/LexicalAnalysis/TokenFactory.cs
@@ -64,8 +64,7 @@ } public Token Create(IEnumerable<Token> tokens, string token, string worksheet) { - Token tokenSeparator = null; - if (_tokenSeparatorProvider.Tokens.TryGetValue(token, out tokenSeparator)) { + if (_tokenSeparatorProvider.Tokens.TryGetValue(token, out var tokenSeparator)) { return tokenSeparator; } var tokenList = (IList<Token>)tokens;
diff --git a/EPPlus/FormulaParsing/LexicalAnalysis/TokenHandler.cs b/EPPlus/FormulaParsing/LexicalAnalysis/TokenHandler.cs deleted file mode 100644 index 8c2a271..0000000 --- a/EPPlus/FormulaParsing/LexicalAnalysis/TokenHandler.cs +++ /dev/null
@@ -1,132 +0,0 @@ -/******************************************************************************* - * You may amend and distribute as you like, but don't remove this header! - * - * EPPlus provides server-side generation of Excel 2007/2010 spreadsheets. - * See http://www.codeplex.com/EPPlus for details. - * - * Copyright (C) 2011 Jan Källman - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php - * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html - * - * All code and executables are provided "as is" with no warranty either express or implied. - * The author accepts no liability for any damage or loss of business that this product may cause. - * - * Code change notes: - * - * Author Change Date - * ****************************************************************************** - * Mats Alm Added 2015-12-28 - *******************************************************************************/ -using System.Text.RegularExpressions; -using OfficeOpenXml.FormulaParsing.LexicalAnalysis.TokenSeparatorHandlers; - -namespace OfficeOpenXml.FormulaParsing.LexicalAnalysis { - public class TokenHandler : ITokenIndexProvider { - public TokenHandler( - TokenizerContext context, - ITokenFactory tokenFactory, - ITokenSeparatorProvider tokenProvider) { - _context = context; - _tokenFactory = tokenFactory; - _tokenProvider = tokenProvider; - } - - private readonly TokenizerContext _context; - private readonly ITokenSeparatorProvider _tokenProvider; - private readonly ITokenFactory _tokenFactory; - private int _tokenIndex = -1; - - public string Worksheet { get; set; } - - public bool HasMore() { - return _tokenIndex < (_context.FormulaChars.Length - 1); - } - - public void Next() { - _tokenIndex++; - Handle(); - } - - private void Handle() { - var c = _context.FormulaChars[_tokenIndex]; - Token tokenSeparator; - if (CharIsTokenSeparator(c, out tokenSeparator)) { - if (TokenSeparatorHandler.Handle(c, tokenSeparator, _context, this)) { - return; - } - - if (_context.CurrentTokenHasValue) { - if (Regex.IsMatch(_context.CurrentToken, "^\"*$")) { - _context.AddToken(_tokenFactory.Create(_context.CurrentToken, TokenType.StringContent)); - } else { - _context.AddToken(CreateToken(_context, Worksheet)); - } - - //If the a next token is an opening parantheses and the previous token is interpeted as an address or name, then the currenct token is a function - if (tokenSeparator.TokenType == TokenType.OpeningParenthesis - && (_context.LastToken.TokenType == TokenType.ExcelAddress - || _context.LastToken.TokenType == TokenType.NameValue)) { - _context.LastToken.TokenType = TokenType.Function; - } - } - if (tokenSeparator.Value == "-") { - if (TokenIsNegator(_context)) { - _context.AddToken(new Token("-", TokenType.Negator)); - return; - } - } - _context.AddToken(tokenSeparator); - _context.NewToken(); - return; - } - _context.AppendToCurrentToken(c); - } - - private bool CharIsTokenSeparator(char c, out Token token) { - var result = _tokenProvider.Tokens.ContainsKey(c.ToString()); - token = result ? token = _tokenProvider.Tokens[c.ToString()] : null; - return result; - } - - private static bool TokenIsNegator(TokenizerContext context) { - return TokenIsNegator(context.LastToken); - } - - private static bool TokenIsNegator(Token t) { - return t == null - || t.TokenType == TokenType.Operator - || t.TokenType == TokenType.OpeningParenthesis - || t.TokenType == TokenType.Comma - || t.TokenType == TokenType.SemiColon - || t.TokenType == TokenType.OpeningEnumerable; - } - - private Token CreateToken(TokenizerContext context, string worksheet) { - if (context.CurrentToken == "-") { - if (context.LastToken == null && context.LastToken.TokenType == TokenType.Operator) { - return new Token("-", TokenType.Negator); - } - } - return _tokenFactory.Create(context.Result, context.CurrentToken, worksheet); - } - - int ITokenIndexProvider.Index { - get { return _tokenIndex; } - } - - void ITokenIndexProvider.MoveIndexPointerForward() { - _tokenIndex++; - } - } -}
diff --git a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/BracketHandler.cs b/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/BracketHandler.cs deleted file mode 100644 index ea4236a..0000000 --- a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/BracketHandler.cs +++ /dev/null
@@ -1,60 +0,0 @@ -/******************************************************************************* - * You may amend and distribute as you like, but don't remove this header! - * - * EPPlus provides server-side generation of Excel 2007/2010 spreadsheets. - * See http://www.codeplex.com/EPPlus for details. - * - * Copyright (C) 2011 Jan Källman - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php - * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html - * - * All code and executables are provided "as is" with no warranty either express or implied. - * The author accepts no liability for any damage or loss of business that this product may cause. - * - * Code change notes: - * - * Author Change Date - * ****************************************************************************** - * Mats Alm Added 2015-12-28 - *******************************************************************************/ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace OfficeOpenXml.FormulaParsing.LexicalAnalysis.TokenSeparatorHandlers { - public class BracketHandler : SeparatorHandler { - public override bool Handle( - char c, - Token tokenSeparator, - TokenizerContext context, - ITokenIndexProvider tokenIndexProvider) { - if (tokenSeparator.TokenType == TokenType.OpeningBracket) { - context.AppendToCurrentToken(c); - context.BracketCount++; - return true; - } - if (tokenSeparator.TokenType == TokenType.ClosingBracket) { - context.AppendToCurrentToken(c); - context.BracketCount--; - return true; - } - if (context.BracketCount > 0) { - context.AppendToCurrentToken(c); - return true; - } - return false; - } - } -}
diff --git a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/MultipleCharSeparatorHandler.cs b/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/MultipleCharSeparatorHandler.cs deleted file mode 100644 index dc02369..0000000 --- a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/MultipleCharSeparatorHandler.cs +++ /dev/null
@@ -1,72 +0,0 @@ -/******************************************************************************* - * You may amend and distribute as you like, but don't remove this header! - * - * EPPlus provides server-side generation of Excel 2007/2010 spreadsheets. - * See http://www.codeplex.com/EPPlus for details. - * - * Copyright (C) 2011 Jan Källman - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php - * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html - * - * All code and executables are provided "as is" with no warranty either express or implied. - * The author accepts no liability for any damage or loss of business that this product may cause. - * - * Code change notes: - * - * Author Change Date - * ****************************************************************************** - * Mats Alm Added 2015-12-28 - *******************************************************************************/ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; - -namespace OfficeOpenXml.FormulaParsing.LexicalAnalysis.TokenSeparatorHandlers { - public class MultipleCharSeparatorHandler : SeparatorHandler { - ITokenSeparatorProvider _tokenSeparatorProvider; - - public MultipleCharSeparatorHandler() - : this(new TokenSeparatorProvider()) {} - - public MultipleCharSeparatorHandler(ITokenSeparatorProvider tokenSeparatorProvider) { - _tokenSeparatorProvider = tokenSeparatorProvider; - } - - public override bool Handle( - char c, - Token tokenSeparator, - TokenizerContext context, - ITokenIndexProvider tokenIndexProvider) { - // two operators in sequence could be "<=" or ">=" - if (IsPartOfMultipleCharSeparator(context, c)) { - var sOp = context.LastToken.Value + c.ToString(CultureInfo.InvariantCulture); - var op = _tokenSeparatorProvider.Tokens[sOp]; - context.ReplaceLastToken(op); - context.NewToken(); - return true; - } - return false; - } - - private bool IsPartOfMultipleCharSeparator(TokenizerContext context, char c) { - var lastToken = context.LastToken != null ? context.LastToken.Value : string.Empty; - return _tokenSeparatorProvider.IsOperator(lastToken) - && _tokenSeparatorProvider.IsPossibleLastPartOfMultipleCharOperator( - c.ToString(CultureInfo.InvariantCulture)) - && !context.CurrentTokenHasValue; - } - } -}
diff --git a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/SeparatorHandler.cs b/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/SeparatorHandler.cs deleted file mode 100644 index 702a12d..0000000 --- a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/SeparatorHandler.cs +++ /dev/null
@@ -1,53 +0,0 @@ -/******************************************************************************* - * You may amend and distribute as you like, but don't remove this header! - * - * EPPlus provides server-side generation of Excel 2007/2010 spreadsheets. - * See http://www.codeplex.com/EPPlus for details. - * - * Copyright (C) 2011 Jan Källman - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php - * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html - * - * All code and executables are provided "as is" with no warranty either express or implied. - * The author accepts no liability for any damage or loss of business that this product may cause. - * - * Code change notes: - * - * Author Change Date - * ****************************************************************************** - * Mats Alm Added 2015-12-28 - *******************************************************************************/ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace OfficeOpenXml.FormulaParsing.LexicalAnalysis.TokenSeparatorHandlers { - public abstract class SeparatorHandler { - protected bool IsDoubleQuote( - Token tokenSeparator, - int formulaCharIndex, - TokenizerContext context) { - return tokenSeparator.TokenType == TokenType.String - && formulaCharIndex + 1 < context.FormulaChars.Length - && context.FormulaChars[formulaCharIndex + 1] == '\"'; - } - - public abstract bool Handle( - char c, - Token tokenSeparator, - TokenizerContext context, - ITokenIndexProvider tokenIndexProvider); - } -}
diff --git a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/SheetnameHandler.cs b/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/SheetnameHandler.cs deleted file mode 100644 index f435fb3..0000000 --- a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/SheetnameHandler.cs +++ /dev/null
@@ -1,70 +0,0 @@ -/******************************************************************************* - * You may amend and distribute as you like, but don't remove this header! - * - * EPPlus provides server-side generation of Excel 2007/2010 spreadsheets. - * See http://www.codeplex.com/EPPlus for details. - * - * Copyright (C) 2011 Jan Källman - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php - * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html - * - * All code and executables are provided "as is" with no warranty either express or implied. - * The author accepts no liability for any damage or loss of business that this product may cause. - * - * Code change notes: - * - * Author Change Date - * ****************************************************************************** - * Mats Alm Added 2015-12-28 - *******************************************************************************/ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace OfficeOpenXml.FormulaParsing.LexicalAnalysis.TokenSeparatorHandlers { - public class SheetnameHandler : SeparatorHandler { - public override bool Handle( - char c, - Token tokenSeparator, - TokenizerContext context, - ITokenIndexProvider tokenIndexProvider) { - if (context.IsInSheetName) { - if (IsDoubleQuote(tokenSeparator, tokenIndexProvider.Index, context)) { - tokenIndexProvider.MoveIndexPointerForward(); - context.AppendToCurrentToken(c); - return true; - } - if (tokenSeparator.TokenType != TokenType.WorksheetName) { - context.AppendToCurrentToken(c); - return true; - } - } - - if (tokenSeparator.TokenType == TokenType.WorksheetName) { - if (context.LastToken != null && context.LastToken.TokenType == TokenType.WorksheetName) { - context.AddToken( - !context.CurrentTokenHasValue - ? new Token(string.Empty, TokenType.WorksheetNameContent) - : new Token(context.CurrentToken, TokenType.WorksheetNameContent)); - } - context.AddToken(new Token("'", TokenType.WorksheetName)); - context.ToggleIsInSheetName(); - context.NewToken(); - return true; - } - return false; - } - } -}
diff --git a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/StringHandler.cs b/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/StringHandler.cs deleted file mode 100644 index 2ef629c..0000000 --- a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/StringHandler.cs +++ /dev/null
@@ -1,76 +0,0 @@ -/******************************************************************************* - * You may amend and distribute as you like, but don't remove this header! - * - * EPPlus provides server-side generation of Excel 2007/2010 spreadsheets. - * See http://www.codeplex.com/EPPlus for details. - * - * Copyright (C) 2011 Jan Källman - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php - * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html - * - * All code and executables are provided "as is" with no warranty either express or implied. - * The author accepts no liability for any damage or loss of business that this product may cause. - * - * Code change notes: - * - * Author Change Date - * ****************************************************************************** - * Mats Alm Added 2015-12-28 - *******************************************************************************/ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace OfficeOpenXml.FormulaParsing.LexicalAnalysis.TokenSeparatorHandlers { - public class StringHandler : SeparatorHandler { - public override bool Handle( - char c, - Token tokenSeparator, - TokenizerContext context, - ITokenIndexProvider tokenIndexProvider) { - if (context.IsInString) { - if (IsDoubleQuote(tokenSeparator, tokenIndexProvider.Index, context)) { - tokenIndexProvider.MoveIndexPointerForward(); - context.AppendToCurrentToken(c); - return true; - } - if (tokenSeparator.TokenType != TokenType.String) { - context.AppendToCurrentToken(c); - return true; - } - } - - if (tokenSeparator.TokenType == TokenType.String) { - if (context.LastToken != null - && context.LastToken.TokenType == TokenType.OpeningEnumerable) { - context.AppendToCurrentToken(c); - context.ToggleIsInString(); - return true; - } - if (context.LastToken != null && context.LastToken.TokenType == TokenType.String) { - context.AddToken( - !context.CurrentTokenHasValue - ? new Token(string.Empty, TokenType.StringContent) - : new Token(context.CurrentToken, TokenType.StringContent)); - } - context.AddToken(new Token("\"", TokenType.String)); - context.ToggleIsInString(); - context.NewToken(); - return true; - } - return false; - } - } -}
diff --git a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/TokenSeparatorHandler.cs b/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/TokenSeparatorHandler.cs deleted file mode 100644 index 8afb997..0000000 --- a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorHandlers/TokenSeparatorHandler.cs +++ /dev/null
@@ -1,70 +0,0 @@ -/******************************************************************************* - * You may amend and distribute as you like, but don't remove this header! - * - * EPPlus provides server-side generation of Excel 2007/2010 spreadsheets. - * See http://www.codeplex.com/EPPlus for details. - * - * Copyright (C) 2011 Jan Källman - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php - * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html - * - * All code and executables are provided "as is" with no warranty either express or implied. - * The author accepts no liability for any damage or loss of business that this product may cause. - * - * Code change notes: - * - * Author Change Date - * ****************************************************************************** - * Mats Alm Added 2015-12-28 - *******************************************************************************/ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace OfficeOpenXml.FormulaParsing.LexicalAnalysis.TokenSeparatorHandlers { - /// <summary> - /// This class provides access to <see cref="SeparatorHandler"/>s - classes that exposes functionatlity - /// needed when parsing strings to tokens. - /// </summary> - public static class TokenSeparatorHandler { - private static SeparatorHandler[] _handlers = new SeparatorHandler[] { - new StringHandler(), - new BracketHandler(), - new SheetnameHandler(), - new MultipleCharSeparatorHandler(), - }; - - /// <summary> - /// Handles a tokenseparator. - /// </summary> - /// <param name="c"></param> - /// <param name="tokenSeparator"></param> - /// <param name="context"></param> - /// <param name="tokenIndexProvider"></param> - /// <returns>Returns true if the tokenseparator was handled.</returns> - public static bool Handle( - char c, - Token tokenSeparator, - TokenizerContext context, - ITokenIndexProvider tokenIndexProvider) { - foreach (var handler in _handlers) { - if (handler.Handle(c, tokenSeparator, context, tokenIndexProvider)) { - return true; - } - } - return false; - } - } -}
diff --git a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorProvider.cs b/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorProvider.cs index cddd2f3..337f2a2 100644 --- a/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorProvider.cs +++ b/EPPlus/FormulaParsing/LexicalAnalysis/TokenSeparatorProvider.cs
@@ -66,8 +66,7 @@ IDictionary<string, Token> ITokenSeparatorProvider.Tokens => _tokens; public bool IsOperator(string item) { - Token token; - if (_tokens.TryGetValue(item, out token)) { + if (_tokens.TryGetValue(item, out var token)) { if (token.TokenType == TokenType.Operator) { return true; }
diff --git a/EPPlus/FormulaParsing/LexicalAnalysis/TokenizerContext.cs b/EPPlus/FormulaParsing/LexicalAnalysis/TokenizerContext.cs index 34fc6f2..ef9c31a 100644 --- a/EPPlus/FormulaParsing/LexicalAnalysis/TokenizerContext.cs +++ b/EPPlus/FormulaParsing/LexicalAnalysis/TokenizerContext.cs
@@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * You may amend and distribute as you like, but don't remove this header! * * EPPlus provides server-side generation of Excel 2007/2010 spreadsheets. @@ -50,9 +50,7 @@ public char[] FormulaChars => _chars; - public IList<Token> Result { - get { return _result; } - } + public IList<Token> Result => _result; public bool IsInString { get; private set; } @@ -62,13 +60,10 @@ internal int BracketCount { get; set; } - public string CurrentToken { - get { return _currentToken.ToString(); } - } + public string CurrentToken => _currentToken.ToString(); - public bool CurrentTokenHasValue { - get { return !string.IsNullOrEmpty(IsInString ? CurrentToken : CurrentToken.Trim()); } - } + public bool CurrentTokenHasValue => + !string.IsNullOrEmpty(IsInString ? CurrentToken : CurrentToken.Trim()); public void NewToken() { _currentToken = new(); @@ -98,7 +93,5 @@ _result.Add(newToken); } - public Token LastToken { - get { return _result.Count > 0 ? _result.Last() : null; } - } + public Token LastToken => _result.Count > 0 ? _result.Last() : null; }
diff --git a/EPPlus/OfficeProperties.cs b/EPPlus/OfficeProperties.cs index d18b047..1b0a6be 100644 --- a/EPPlus/OfficeProperties.cs +++ b/EPPlus/OfficeProperties.cs
@@ -204,12 +204,10 @@ /// Gets/sets the created property of the document (core property) /// </summary> public DateTime Created { - get { - DateTime date; - return DateTime.TryParse(_coreHelper.GetXmlNodeString(_createdPath), out date) + get => + DateTime.TryParse(_coreHelper.GetXmlNodeString(_createdPath), out var date) ? date : DateTime.MinValue; - } set { var dateString = value.ToUniversalTime().ToString("s", CultureInfo.InvariantCulture) + "Z"; _coreHelper.SetXmlNodeString(_createdPath, dateString); @@ -312,12 +310,10 @@ /// Gets/sets the modified property of the document (core property) /// </summary> public DateTime Modified { - get { - DateTime date; - return DateTime.TryParse(_coreHelper.GetXmlNodeString(_modifiedPath), out date) + get => + DateTime.TryParse(_coreHelper.GetXmlNodeString(_modifiedPath), out var date) ? date : DateTime.MinValue; - } set { var dateString = value.ToUniversalTime().ToString("s", CultureInfo.InvariantCulture) + "Z"; _coreHelper.SetXmlNodeString(_modifiedPath, dateString); @@ -325,16 +321,6 @@ } } - private string GetExtendedPropertyValue(string propertyName) { - string retValue = null; - string searchString = string.Format("xp:Properties/xp:{0}", propertyName); - XmlNode node = ExtendedPropertiesXml.SelectSingleNode(searchString, NameSpaceManager); - if (node != null) { - retValue = node.InnerText; - } - return retValue; - } - /// <summary> /// Provides access to the XML document which holds the document's custom properties /// </summary> @@ -367,20 +353,17 @@ string value = node.LastChild.InnerText; switch (node.LastChild.LocalName) { case "filetime": - DateTime dt; - if (DateTime.TryParse(value, out dt)) { + if (DateTime.TryParse(value, out var dt)) { return dt; } return null; case "i4": - int i; - if (int.TryParse(value, out i)) { + if (int.TryParse(value, out var i)) { return i; } return null; case "r8": - double d; - if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out d)) { + if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var d)) { return d; } return null; @@ -437,20 +420,20 @@ if (value is bool) { valueElem = CustomPropertiesXml.CreateElement("vt", "bool", ExcelPackage._schemaVt); valueElem.InnerText = value.ToString().ToLower(CultureInfo.InvariantCulture); - } else if (value is DateTime) { + } else if (value is DateTime time) { valueElem = CustomPropertiesXml.CreateElement("vt", "filetime", ExcelPackage._schemaVt); - valueElem.InnerText = ((DateTime)value).AddHours(-1).ToString("yyyy-MM-ddTHH:mm:ssZ"); + valueElem.InnerText = time.AddHours(-1).ToString("yyyy-MM-ddTHH:mm:ssZ"); } else if (value is short || value is int) { valueElem = CustomPropertiesXml.CreateElement("vt", "i4", ExcelPackage._schemaVt); valueElem.InnerText = value.ToString(); } else if (value is double || value is decimal || value is float || value is long) { valueElem = CustomPropertiesXml.CreateElement("vt", "r8", ExcelPackage._schemaVt); - if (value is double) { - valueElem.InnerText = ((double)value).ToString(CultureInfo.InvariantCulture); - } else if (value is float) { - valueElem.InnerText = ((float)value).ToString(CultureInfo.InvariantCulture); - } else if (value is decimal) { - valueElem.InnerText = ((decimal)value).ToString(CultureInfo.InvariantCulture); + if (value is double d) { + valueElem.InnerText = d.ToString(CultureInfo.InvariantCulture); + } else if (value is float f) { + valueElem.InnerText = f.ToString(CultureInfo.InvariantCulture); + } else if (value is decimal value1) { + valueElem.InnerText = value1.ToString(CultureInfo.InvariantCulture); } else { valueElem.InnerText = value.ToString(); }
diff --git a/EPPlus/OpenOfficeXml.snk b/EPPlus/OpenOfficeXml.snk deleted file mode 100644 index a8067be..0000000 --- a/EPPlus/OpenOfficeXml.snk +++ /dev/null Binary files differ
diff --git a/EPPlus/Packaging/ZipPackageRelationshipBase.cs b/EPPlus/Packaging/ZipPackageRelationshipBase.cs index 6c0411f..882358e 100644 --- a/EPPlus/Packaging/ZipPackageRelationshipBase.cs +++ b/EPPlus/Packaging/ZipPackageRelationshipBase.cs
@@ -46,8 +46,7 @@ protected void UpdateMaxRId(string id, ref int maxRId) { if (id.StartsWith("rId")) { - int num; - if (int.TryParse(id.Substring(3), out num)) { + if (int.TryParse(id.Substring(3), out var num)) { if (num == maxRId - 1) { maxRId--; } @@ -108,8 +107,7 @@ rel.SourceUri = new(source, UriKind.Relative); } if (rel.Id.StartsWith("rid", StringComparison.InvariantCultureIgnoreCase)) { - int id; - if (int.TryParse(rel.Id.Substring(3), out id)) { + if (int.TryParse(rel.Id.Substring(3), out var id)) { if (id >= maxRId && id < int.MaxValue
diff --git a/EPPlus/Packaging/ZipPackageRelationshipCollection.cs b/EPPlus/Packaging/ZipPackageRelationshipCollection.cs index dab1030..f828f61 100644 --- a/EPPlus/Packaging/ZipPackageRelationshipCollection.cs +++ b/EPPlus/Packaging/ZipPackageRelationshipCollection.cs
@@ -91,7 +91,5 @@ writer.Write("</Relationships>"); } - public int Count { - get { return _rels.Count; } - } + public int Count => _rels.Count; }
diff --git a/EPPlus/Properties/AssemblyInfo.cs b/EPPlus/Properties/AssemblyInfo.cs deleted file mode 100644 index 2fc9137..0000000 --- a/EPPlus/Properties/AssemblyInfo.cs +++ /dev/null
@@ -1,68 +0,0 @@ -/******************************************************************************* - * You may amend and distribute as you like, but don't remove this header! - * - * EPPlus provides server-side generation of Excel 2007/2010 spreadsheets. - * See http://www.codeplex.com/EPPlus for details. - * - * Copyright (C) 2011 Jan Källman - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php - * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html - * - * All code and executables are provided "as is" with no warranty either express or implied. - * The author accepts no liability for any damage or loss of business that this product may cause. - * - * Code change notes: - * - * Author Change Date - ******************************************************************************* - * Jan Källman Added 10-SEP-2009 - * Jan Källman License changed GPL-->LGPL 2011-12-27 - *******************************************************************************/ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Security; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("EPPlus 4.0.4")] -[assembly: AssemblyDescription( - "Allows Excel files(xlsx;xlsm) to be created on the server. See epplus.codeplex.com")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("EPPlus")] -[assembly: AssemblyProduct("EPPlus 4.0.4")] -[assembly: AssemblyCopyright( - "Copyright 2009- ©Jan Källman. Parts of the Interface comes from ExcelPackage-project")] -[assembly: AssemblyTrademark("The GNU Lesser General Public License (LGPL)")] -[assembly: AssemblyCulture("")] -[assembly: ComVisible(false)] -[assembly: InternalsVisibleTo( - "EPPlusTest, PublicKey=00240000048000009400000006020000002400005253413100040000010001001dd11308ec93a6ebcec727e183a8972dc6f95c23ecc34aa04f40cbfc9c17b08b4a0ea5c00dcd203bace44d15a30ce8796e38176ae88e960ceff9cc439ab938738ba0e603e3d155fc298799b391c004fc0eb4393dd254ce25db341eb43303e4c488c9500e126f1288594f0710ec7d642e9c72e76dd860649f1c48249c00e31fba")] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("9dd43b8d-c4fe-4a8b-ad6e-47ef83bbbb01")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("4.0.4.0")] -[assembly: AssemblyFileVersion("4.0.4.0")] -[assembly: AllowPartiallyTrustedCallers]
diff --git a/EPPlus/RangeCollection.cs b/EPPlus/RangeCollection.cs index 90fbfb9..5dfb567 100644 --- a/EPPlus/RangeCollection.cs +++ b/EPPlus/RangeCollection.cs
@@ -101,9 +101,7 @@ /// </summary> /// <param name="index"></param> /// <returns></returns> - internal IRangeId this[int index] { - get { return _cells[_cellIndex[index].ListPointer]; } - } + internal IRangeId this[int index] => _cells[_cellIndex[index].ListPointer]; internal int Count { get { return _cells.Count; }
diff --git a/EPPlus/Style/ExcelParagraphCollection.cs b/EPPlus/Style/ExcelParagraphCollection.cs index 784c4cc..a74fe57 100644 --- a/EPPlus/Style/ExcelParagraphCollection.cs +++ b/EPPlus/Style/ExcelParagraphCollection.cs
@@ -71,8 +71,8 @@ /// <returns></returns> public ExcelParagraph Add(string text) { XmlDocument doc; - if (TopNode is XmlDocument) { - doc = TopNode as XmlDocument; + if (TopNode is XmlDocument document) { + doc = document; } else { doc = TopNode.OwnerDocument; }
diff --git a/EPPlus/Style/ExcelRichTextCollection.cs b/EPPlus/Style/ExcelRichTextCollection.cs index 0f4e29d..5e87c4b 100644 --- a/EPPlus/Style/ExcelRichTextCollection.cs +++ b/EPPlus/Style/ExcelRichTextCollection.cs
@@ -90,8 +90,8 @@ public ExcelRichText Add(string text) { ConvertRichtext(); XmlDocument doc; - if (TopNode is XmlDocument) { - doc = TopNode as XmlDocument; + if (TopNode is XmlDocument document) { + doc = document; } else { doc = TopNode.OwnerDocument; } @@ -161,9 +161,8 @@ this[0].Size = fnt.Size; this[0].UnderLine = fnt.UnderLine; - int hex; if (fnt.Color.Rgb != "" - && int.TryParse(fnt.Color.Rgb, NumberStyles.HexNumber, null, out hex)) { + && int.TryParse(fnt.Color.Rgb, NumberStyles.HexNumber, null, out var hex)) { this[0].Color = Color.FromArgb(hex); } }
diff --git a/EPPlus/Style/ExcelStyle.cs b/EPPlus/Style/ExcelStyle.cs index f9ad943..9c2509a 100644 --- a/EPPlus/Style/ExcelStyle.cs +++ b/EPPlus/Style/ExcelStyle.cs
@@ -190,8 +190,6 @@ new(eStyleClass.Style, eStyleProperty.Hidden, value, _positionID, _address)); } - private const string _xfIdPath = "@xfId"; - /// <summary> /// The index in the style collection /// </summary>
diff --git a/EPPlus/Style/XmlAccess/ExcelBorderXml.cs b/EPPlus/Style/XmlAccess/ExcelBorderXml.cs index 9a7e12c..9d19974 100644 --- a/EPPlus/Style/XmlAccess/ExcelBorderXml.cs +++ b/EPPlus/Style/XmlAccess/ExcelBorderXml.cs
@@ -62,8 +62,8 @@ /// Left border style properties /// </summary> public ExcelBorderItemXml Left { - get { return _left; } - internal set { _left = value; } + get => _left; + internal set => _left = value; } private const string _rightPath = "d:right"; @@ -73,8 +73,8 @@ /// Right border style properties /// </summary> public ExcelBorderItemXml Right { - get { return _right; } - internal set { _right = value; } + get => _right; + internal set => _right = value; } private const string _topPath = "d:top"; @@ -84,8 +84,8 @@ /// Top border style properties /// </summary> public ExcelBorderItemXml Top { - get { return _top; } - internal set { _top = value; } + get => _top; + internal set => _top = value; } private const string _bottomPath = "d:bottom"; @@ -95,8 +95,8 @@ /// Bottom border style properties /// </summary> public ExcelBorderItemXml Bottom { - get { return _bottom; } - internal set { _bottom = value; } + get => _bottom; + internal set => _bottom = value; } private const string _diagonalPath = "d:diagonal"; @@ -106,8 +106,8 @@ /// Diagonal border style properties /// </summary> public ExcelBorderItemXml Diagonal { - get { return _diagonal; } - internal set { _diagonal = value; } + get => _diagonal; + internal set => _diagonal = value; } private const string _diagonalUpPath = "@diagonalUp"; @@ -117,8 +117,8 @@ /// Diagonal up border /// </summary> public bool DiagonalUp { - get { return _diagonalUp; } - internal set { _diagonalUp = value; } + get => _diagonalUp; + internal set => _diagonalUp = value; } private const string _diagonalDownPath = "@diagonalDown"; @@ -128,8 +128,8 @@ /// Diagonal down border /// </summary> public bool DiagonalDown { - get { return _diagonalDown; } - internal set { _diagonalDown = value; } + get => _diagonalDown; + internal set => _diagonalDown = value; } internal ExcelBorderXml Copy() {
diff --git a/EPPlus/Style/XmlAccess/ExcelFontXml.cs b/EPPlus/Style/XmlAccess/ExcelFontXml.cs index 11b6bb9..88ab554 100644 --- a/EPPlus/Style/XmlAccess/ExcelFontXml.cs +++ b/EPPlus/Style/XmlAccess/ExcelFontXml.cs
@@ -106,7 +106,7 @@ /// The name of the font /// </summary> public string Name { - get { return _name; } + get => _name; set { Scheme = ""; //Reset schema to avoid corrupt file if unsupported font is selected. _name = value; @@ -120,8 +120,8 @@ /// Font size /// </summary> public float Size { - get { return _size; } - set { _size = value; } + get => _size; + set => _size = value; } private const string _familyPath = "d:family/@val"; @@ -131,11 +131,8 @@ /// Font family /// </summary> public int Family { - get { - return (_family == int.MinValue ? 0 : _family); - ; - } - set { _family = value; } + get => (_family == int.MinValue ? 0 : _family); + set => _family = value; } private ExcelColorXml _color; @@ -145,8 +142,8 @@ /// Text color /// </summary> public ExcelColorXml Color { - get { return _color; } - internal set { _color = value; } + get => _color; + internal set => _color = value; } private const string _schemePath = "d:scheme/@val"; @@ -156,8 +153,8 @@ /// Font Scheme /// </summary> public string Scheme { - get { return _scheme; } - private set { _scheme = value; } + get => _scheme; + private set => _scheme = value; } private const string _boldPath = "d:b"; @@ -167,8 +164,8 @@ /// If the font is bold /// </summary> public bool Bold { - get { return _bold; } - set { _bold = value; } + get => _bold; + set => _bold = value; } private const string _italicPath = "d:i"; @@ -178,8 +175,8 @@ /// If the font is italic /// </summary> public bool Italic { - get { return _italic; } - set { _italic = value; } + get => _italic; + set => _italic = value; } private const string _strikePath = "d:strike"; @@ -189,8 +186,8 @@ /// If the font is striked out /// </summary> public bool Strike { - get { return _strike; } - set { _strike = value; } + get => _strike; + set => _strike = value; } private const string _underLinedPath = "d:u"; @@ -200,8 +197,8 @@ /// When set to true a the text is underlined with a single line /// </summary> public bool UnderLine { - get { return UnderLineType != ExcelUnderLineType.None; } - set { _underlineType = value ? ExcelUnderLineType.Single : ExcelUnderLineType.None; } + get => UnderLineType != ExcelUnderLineType.None; + set => _underlineType = value ? ExcelUnderLineType.Single : ExcelUnderLineType.None; } private ExcelUnderLineType _underlineType; @@ -210,8 +207,8 @@ /// If the font is underlined /// </summary> public ExcelUnderLineType UnderLineType { - get { return _underlineType; } - set { _underlineType = value; } + get => _underlineType; + set => _underlineType = value; } private const string _verticalAlignPath = "d:vertAlign/@val"; @@ -221,8 +218,8 @@ /// Vertical aligned /// </summary> public string VerticalAlign { - get { return _verticalAlign; } - set { _verticalAlign = value; } + get => _verticalAlign; + set => _verticalAlign = value; } public void SetFromFont(Font font) {
diff --git a/EPPlus/Style/XmlAccess/ExcelNumberFormatXml.cs b/EPPlus/Style/XmlAccess/ExcelNumberFormatXml.cs index 0d0b46f..6e5d10d 100644 --- a/EPPlus/Style/XmlAccess/ExcelNumberFormatXml.cs +++ b/EPPlus/Style/XmlAccess/ExcelNumberFormatXml.cs
@@ -103,7 +103,6 @@ internal override string Id => _format; - private const string _fmtPath = "@formatCode"; private string _format = string.Empty; public string Format { @@ -603,8 +602,7 @@ string[] fmt = FractionFormat.Split('/'); - int fixedDenominator; - if (!int.TryParse(fmt[1], out fixedDenominator)) { + if (!int.TryParse(fmt[1], out var fixedDenominator)) { fixedDenominator = 0; }
diff --git a/EPPlus/Table/ExcelTable.cs b/EPPlus/Table/ExcelTable.cs index 0b9144a..2438154 100644 --- a/EPPlus/Table/ExcelTable.cs +++ b/EPPlus/Table/ExcelTable.cs
@@ -358,7 +358,6 @@ } private const string _totalsrowcountPath = "@totalsRowCount"; - private const string _totalsrowshownPath = "@totalsRowShown"; /// <summary> /// If the total row is visible or not
diff --git a/EPPlus/Table/PivotTable/ExcelPivotTable.cs b/EPPlus/Table/PivotTable/ExcelPivotTable.cs index 75c6360..6ea4244 100644 --- a/EPPlus/Table/PivotTable/ExcelPivotTable.cs +++ b/EPPlus/Table/PivotTable/ExcelPivotTable.cs
@@ -62,8 +62,7 @@ //Add row fields. foreach (XmlElement rowElem in TopNode.SelectNodes("d:rowFields/d:field", NameSpaceManager)) { - int x; - if (int.TryParse(rowElem.GetAttribute("x"), out x) && x >= 0) { + if (int.TryParse(rowElem.GetAttribute("x"), out var x) && x >= 0) { RowFields.AddInternal(Fields[x]); } else { rowElem.ParentNode.RemoveChild(rowElem); @@ -72,8 +71,7 @@ ////Add column fields. foreach (XmlElement colElem in TopNode.SelectNodes("d:colFields/d:field", NameSpaceManager)) { - int x; - if (int.TryParse(colElem.GetAttribute("x"), out x) && x >= 0) { + if (int.TryParse(colElem.GetAttribute("x"), out var x) && x >= 0) { ColumnFields.AddInternal(Fields[x]); } else { colElem.ParentNode.RemoveChild(colElem); @@ -85,8 +83,7 @@ foreach (XmlElement pageElem in TopNode.SelectNodes( "d:pageFields/d:pageField", NameSpaceManager)) { - int fld; - if (int.TryParse(pageElem.GetAttribute("fld"), out fld) && fld >= 0) { + if (int.TryParse(pageElem.GetAttribute("fld"), out var fld) && fld >= 0) { var field = Fields[fld]; field._pageFieldSettings = new(NameSpaceManager, pageElem, field, fld); PageFields.AddInternal(field); @@ -98,8 +95,7 @@ foreach (XmlElement dataElem in TopNode.SelectNodes( "d:dataFields/d:dataField", NameSpaceManager)) { - int fld; - if (int.TryParse(dataElem.GetAttribute("fld"), out fld) && fld >= 0) { + if (int.TryParse(dataElem.GetAttribute("fld"), out var fld) && fld >= 0) { var field = Fields[fld]; var dataField = new ExcelPivotTableDataField(NameSpaceManager, dataElem, field); DataFields.AddInternal(dataField);
diff --git a/EPPlus/Table/PivotTable/ExcelPivotTableField.cs b/EPPlus/Table/PivotTable/ExcelPivotTableField.cs index 654ab71..9869a11 100644 --- a/EPPlus/Table/PivotTable/ExcelPivotTableField.cs +++ b/EPPlus/Table/PivotTable/ExcelPivotTableField.cs
@@ -507,8 +507,7 @@ newElement; foreach (XmlElement field in rowsNode.ChildNodes) { string x = field.GetAttribute(indexAttrText); - int fieldIndex; - if (int.TryParse(x, out fieldIndex)) { + if (int.TryParse(x, out var fieldIndex)) { if (fieldIndex == index) //Row already exists { @@ -955,10 +954,9 @@ rowColFields = TopNode.SelectSingleNode("../../d:colFields", NameSpaceManager); } - int fieldIndex, - index = 0; + var index = 0; foreach (XmlElement rowfield in rowColFields.ChildNodes) { - if (int.TryParse(rowfield.GetAttribute("x"), out fieldIndex)) { + if (int.TryParse(rowfield.GetAttribute("x"), out var fieldIndex)) { if (_table.Fields[fieldIndex].BaseIndex == BaseIndex) { var newElement = rowColFields.OwnerDocument.CreateElement( "field",
diff --git a/EPPlus/Table/PivotTable/ExcelPivotTableFieldCollection.cs b/EPPlus/Table/PivotTable/ExcelPivotTableFieldCollection.cs index e60e735..5f7053d 100644 --- a/EPPlus/Table/PivotTable/ExcelPivotTableFieldCollection.cs +++ b/EPPlus/Table/PivotTable/ExcelPivotTableFieldCollection.cs
@@ -105,8 +105,7 @@ /// <returns>The matching field. If none is found null is returned</returns> public ExcelPivotTableField GetDateGroupField(eDateGroupBy groupBy) { foreach (var fld in _list) { - if (fld.Grouping is ExcelPivotTableFieldDateGroup - && (((ExcelPivotTableFieldDateGroup)fld.Grouping).GroupBy) == groupBy) { + if (fld.Grouping is ExcelPivotTableFieldDateGroup group && (group.GroupBy) == groupBy) { return fld; } }
diff --git a/EPPlus/Table/PivotTable/ExcelPivotTableFieldGroup.cs b/EPPlus/Table/PivotTable/ExcelPivotTableFieldGroup.cs index ea1f9d4..99fbd3c 100644 --- a/EPPlus/Table/PivotTable/ExcelPivotTableFieldGroup.cs +++ b/EPPlus/Table/PivotTable/ExcelPivotTableFieldGroup.cs
@@ -91,29 +91,19 @@ /// <summary> /// Start value /// </summary> - public double Start { - get => (double)GetXmlNodeDoubleNull(_startPath); - private set => SetXmlNodeString(_startPath, value.ToString(CultureInfo.InvariantCulture)); - } + public double Start => (double)GetXmlNodeDoubleNull(_startPath); private const string _endPath = "d:fieldGroup/d:rangePr/@endNum"; /// <summary> /// End value /// </summary> - public double End { - get => (double)GetXmlNodeDoubleNull(_endPath); - private set => SetXmlNodeString(_endPath, value.ToString(CultureInfo.InvariantCulture)); - } + public double End => (double)GetXmlNodeDoubleNull(_endPath); private const string _groupIntervalPath = "d:fieldGroup/d:rangePr/@groupInterval"; /// <summary> /// Interval /// </summary> - public double Interval { - get => (double)GetXmlNodeDoubleNull(_groupIntervalPath); - private set => - SetXmlNodeString(_groupIntervalPath, value.ToString(CultureInfo.InvariantCulture)); - } + public double Interval => (double)GetXmlNodeDoubleNull(_groupIntervalPath); }
diff --git a/EPPlus/Utils/ConvertUtil.cs b/EPPlus/Utils/ConvertUtil.cs index fddf785..2802caa 100644 --- a/EPPlus/Utils/ConvertUtil.cs +++ b/EPPlus/Utils/ConvertUtil.cs
@@ -39,10 +39,10 @@ return 0; } if (IsNumeric(v)) { - if (v is DateTime) { - d = ((DateTime)v).ToOADate(); - } else if (v is TimeSpan) { - d = DateTime.FromOADate(0).Add((TimeSpan)v).ToOADate(); + if (v is DateTime time) { + d = time.ToOADate(); + } else if (v is TimeSpan span) { + d = DateTime.FromOADate(0).Add(span).ToOADate(); } else { d = Convert.ToDouble(v, CultureInfo.InvariantCulture); }
diff --git a/EPPlus/XmlHelper.cs b/EPPlus/XmlHelper.cs index 9455242..a958baf 100644 --- a/EPPlus/XmlHelper.cs +++ b/EPPlus/XmlHelper.cs
@@ -442,8 +442,8 @@ foreach (string s in split) { node = node.SelectSingleNode(s, NameSpaceManager); if (node != null) { - if (node is XmlAttribute) { - (node as XmlAttribute).OwnerElement.Attributes.Remove(node as XmlAttribute); + if (node is XmlAttribute attribute) { + attribute.OwnerElement.Attributes.Remove(attribute); } else { node.ParentNode.RemoveChild(node); } @@ -456,8 +456,7 @@ internal void DeleteNode(string path) { var node = TopNode.SelectSingleNode(path, NameSpaceManager); if (node != null) { - if (node is XmlAttribute) { - var att = (XmlAttribute)node; + if (node is XmlAttribute att) { att.OwnerElement.Attributes.Remove(att); } else { node.ParentNode.RemoveChild(node); @@ -515,8 +514,8 @@ if (value == removeIf) { var node = TopNode.SelectSingleNode(path, NameSpaceManager); if (node != null) { - if (node is XmlAttribute) { - var elem = (node as XmlAttribute).OwnerElement; + if (node is XmlAttribute attribute) { + var elem = attribute.OwnerElement; elem.ParentNode.RemoveChild(elem); } else { TopNode.RemoveChild(node); @@ -560,41 +559,37 @@ } internal int GetXmlNodeInt(string path) { - int i; - if (int.TryParse(GetXmlNodeString(path), out i)) { + if (int.TryParse(GetXmlNodeString(path), out var i)) { return i; } return int.MinValue; } internal int? GetXmlNodeIntNull(string path) { - int i; string s = GetXmlNodeString(path); - if (s != "" && int.TryParse(s, out i)) { + if (s != "" && int.TryParse(s, out var i)) { return i; } return null; } internal decimal GetXmlNodeDecimal(string path) { - decimal d; if (decimal.TryParse( GetXmlNodeString(path), NumberStyles.Any, CultureInfo.InvariantCulture, - out d)) { + out var d)) { return d; } return 0; } internal decimal? GetXmlNodeDecimalNull(string path) { - decimal d; if (decimal.TryParse( GetXmlNodeString(path), NumberStyles.Any, CultureInfo.InvariantCulture, - out d)) { + out var d)) { return d; } return null; @@ -605,8 +600,7 @@ if (s == "") { return null; } - double v; - if (double.TryParse(s, NumberStyles.Number, CultureInfo.InvariantCulture, out v)) { + if (double.TryParse(s, NumberStyles.Number, CultureInfo.InvariantCulture, out var v)) { return v; } return null; @@ -617,8 +611,7 @@ if (s == "") { return double.NaN; } - double v; - if (double.TryParse(s, NumberStyles.Number, CultureInfo.InvariantCulture, out v)) { + if (double.TryParse(s, NumberStyles.Number, CultureInfo.InvariantCulture, out var v)) { return v; } return double.NaN; @@ -633,7 +626,7 @@ if (nameNode != null) { if (nameNode.NodeType == XmlNodeType.Attribute) { - return nameNode.Value != null ? nameNode.Value : ""; + return nameNode.Value ?? ""; } return nameNode.InnerText; }
diff --git a/NetCoreTests/NetCoreTests.csproj b/NetCoreTests/NetCoreTests.csproj index b5e9414..9af6cc5 100644 --- a/NetCoreTests/NetCoreTests.csproj +++ b/NetCoreTests/NetCoreTests.csproj
@@ -8,15 +8,9 @@ <PackageReference Include="MSTest.TestAdapter" Version="2.2.8"/> <PackageReference Include="MSTest.TestFramework" Version="2.2.8"/> <PackageReference Include="Microsoft.NET.Test.SDK" Version="17.1.0"/> - <PackageReference Include="System.Net.Http" Version="4.3.4"/> - <PackageReference Include="System.Text.Encoding.CodePages" Version="5.0.0"/> - <PackageReference Include="System.Text.RegularExpressions" Version="4.3.1"/> <ProjectReference Include="..\EPPlus\EPPlusSDK.csproj"/> <None Include="TestWorkbooks/**" CopyToOutputDirectory="PreserveNewest"/> - - <!--Transient dependency; required to address b/230278644--> - <PackageReference Include="Newtonsoft.Json" Version="13.0.1"/> </ItemGroup> </Project>