diff --git a/Directory.Build.props b/Directory.Build.props index 8903e0422..c9bedebdf 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -87,7 +87,6 @@ $(NoWarn);CA1834 $(NoWarn);CA1845 $(NoWarn);CA1850 - $(NoWarn);CA1859 $(NoWarn);CA1861 $(NoWarn);CA1862 $(NoWarn);CA1872 diff --git a/main/DDF/AbstractEscherOptRecord.cs b/main/DDF/AbstractEscherOptRecord.cs index 80e267a9c..167570999 100644 --- a/main/DDF/AbstractEscherOptRecord.cs +++ b/main/DDF/AbstractEscherOptRecord.cs @@ -155,11 +155,9 @@ exists it is replaced. */ public void SetEscherProperty(EscherProperty value) { - List toRemove = new List(); - for (IEnumerator iterator = - properties.GetEnumerator(); iterator.MoveNext(); ) + List toRemove = []; + foreach (var prop in properties) { - EscherProperty prop = iterator.Current; if (prop.Id == value.Id) { //iterator.Remove(); @@ -174,18 +172,20 @@ public void SetEscherProperty(EscherProperty value) public void RemoveEscherProperty(int num) { - List toRemove = new List(); - for (IEnumerator iterator = EscherProperties.GetEnumerator(); iterator.MoveNext(); ) + List toRemove = []; + foreach(var prop in EscherProperties) { - EscherProperty prop = iterator.Current; if (prop.PropertyNumber == num) { //iterator.Remove(); toRemove.Add(prop); } } - foreach (EscherProperty e in toRemove) + + foreach(EscherProperty e in toRemove) + { EscherProperties.Remove(e); + } } /** diff --git a/main/DDF/EscherContainerRecord.cs b/main/DDF/EscherContainerRecord.cs index 8d91661d6..8ad72d24d 100644 --- a/main/DDF/EscherContainerRecord.cs +++ b/main/DDF/EscherContainerRecord.cs @@ -211,10 +211,9 @@ public IList ChildContainers { get { - IList containers = new List(); - for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) + List containers = []; + foreach (EscherRecord r in ChildRecords) { - EscherRecord r = (EscherRecord)iterator.Current; if (r is EscherContainerRecord record) { containers.Add(record); @@ -344,9 +343,8 @@ public override String ToXml(String tab) { StringBuilder builder = new StringBuilder(); builder.Append(tab).Append(FormatXmlRecordHeader(RecordName, HexDump.ToHex(RecordId), HexDump.ToHex(Version), HexDump.ToHex(Instance))); - for (IEnumerator iterator = _childRecords.GetEnumerator(); iterator.MoveNext(); ) + foreach (var record in _childRecords) { - EscherRecord record = iterator.Current; builder.Append(record.ToXml(tab + "\t")); } builder.Append(tab).Append("\n"); diff --git a/main/DDF/EscherDump.cs b/main/DDF/EscherDump.cs index 40eacf08b..672665485 100644 --- a/main/DDF/EscherDump.cs +++ b/main/DDF/EscherDump.cs @@ -48,7 +48,7 @@ public EscherDump() /// The number of bytes to Read. public void Dump(byte[] data, int offset, int size) { - IEscherRecordFactory recordFactory = new DefaultEscherRecordFactory(); + DefaultEscherRecordFactory recordFactory = new(); int pos = offset; while (pos < offset + size) { diff --git a/main/DDF/UnknownEscherRecord.cs b/main/DDF/UnknownEscherRecord.cs index 028417dc6..1d95bee76 100644 --- a/main/DDF/UnknownEscherRecord.cs +++ b/main/DDF/UnknownEscherRecord.cs @@ -222,11 +222,12 @@ public override String ToXml(String tab) builder.Append(tab).Append(FormatXmlRecordHeader(GetType().Name, HexDump.ToHex(RecordId), HexDump.ToHex(Version), HexDump.ToHex(Instance))) .Append(tab).Append("\t").Append("").Append(IsContainerRecord).Append("\n") .Append(tab).Append("\t").Append("").Append(HexDump.ToHex(_childRecords.Count)).Append("\n"); - for (IEnumerator iterator = _childRecords.GetEnumerator(); iterator.MoveNext(); ) + + foreach (EscherRecord record in _childRecords) { - EscherRecord record = iterator.Current; builder.Append(record.ToXml(tab + "\t")); } + builder.Append(theDumpHex).Append("\n"); builder.Append(tab).Append("\n"); return builder.ToString(); diff --git a/main/HPSF/CustomProperties.cs b/main/HPSF/CustomProperties.cs index f59352d58..6bfb5d002 100644 --- a/main/HPSF/CustomProperties.cs +++ b/main/HPSF/CustomProperties.cs @@ -64,7 +64,8 @@ public class CustomProperties : Dictionary /// //private TreeBidiDictionary dictionary = new TreeBidiDictionary(); - private BidirectionalDictionary dictionary = new(); + private readonly BidirectionalDictionary dictionary = new(); + /// /// Tells whether this object is pure or not. /// @@ -129,7 +130,7 @@ public CustomProperty Put(String name, CustomProperty cp) /// customProperty /// there was already a property with the same name, the old property /// ClassCastException - private object Put(CustomProperty customProperty) + private CustomProperty Put(CustomProperty customProperty) { string name = customProperty.Name; diff --git a/main/HPSF/PropertySetFactory.cs b/main/HPSF/PropertySetFactory.cs index 9ea3b8986..76a61731a 100644 --- a/main/HPSF/PropertySetFactory.cs +++ b/main/HPSF/PropertySetFactory.cs @@ -25,14 +25,14 @@ limitations under the License. * * ==============================================================*/ +using System; + +using NPOI.HPSF.Wellknown; +using NPOI.POIFS.FileSystem; using NPOI.Util; namespace NPOI.HPSF { - using System.IO; - using NPOI.HPSF.Wellknown; - using System; - using NPOI.POIFS.FileSystem; /// /// Factory class To Create instances of {@link SummaryInformation}, @@ -63,7 +63,7 @@ public class PropertySetFactory */ public static PropertySet Create(DirectoryEntry dir, String name) { - InputStream inp = null; + DocumentInputStream inp = null; try { DocumentEntry entry = (DocumentEntry)dir.GetEntry(name); diff --git a/main/HPSF/Section.cs b/main/HPSF/Section.cs index 8d0e05ae3..c1d5fd402 100644 --- a/main/HPSF/Section.cs +++ b/main/HPSF/Section.cs @@ -26,8 +26,7 @@ namespace NPOI.HPSF using System.Collections.Generic; using System.Linq; using System.IO; - using System.Text; -using Cysharp.Text; + using Cysharp.Text; /// /// Represents a section in a {@link PropertySet}. @@ -956,7 +955,7 @@ public int Write(Stream out1) /// The codepage to be used to write the dictionary items. /// number of bytes written /// if an I/O exception occurs. - private static int WriteDictionary(Stream out1, IDictionary dictionary, int codepage) + private static int WriteDictionary(MemoryStream out1, IDictionary dictionary, int codepage) { int length = TypeWriter.WriteUIntToStream(out1, (uint)dictionary.Count); foreach(DictionaryEntry ls in dictionary) diff --git a/main/HPSF/Variant.cs b/main/HPSF/Variant.cs index 2e8a773b3..1fe21f618 100644 --- a/main/HPSF/Variant.cs +++ b/main/HPSF/Variant.cs @@ -25,12 +25,11 @@ limitations under the License. * * ==============================================================*/ +using System; +using System.Collections.Generic; + namespace NPOI.HPSF { - using System; - using System.Collections; - - /// /// The Variant types as defined by Microsoft's COM. I /// found this information in @@ -358,9 +357,9 @@ public class Variant * Maps the numbers denoting the variant types To their corresponding * variant type names. */ - private static IDictionary numberToName; + private static readonly Dictionary numberToName; - private static IDictionary numberToLength; + private static readonly Dictionary numberToLength; /** * Denotes a variant type with a Length that is unknown To HPSF yet. @@ -397,7 +396,7 @@ public class Variant static Variant() { /* Initialize the number-to-name map: */ - Hashtable tm1 = new Hashtable(); + Dictionary tm1 = []; tm1[0] = "VT_EMPTY"; tm1[1] = "VT_NULL"; tm1[2] = "VT_I2"; @@ -442,7 +441,7 @@ static Variant() numberToName = tm1; /* Initialize the number-to-Length map: */ - Hashtable tm2 = new Hashtable(); + Dictionary tm2 = []; tm2[0] = Length_0; tm2[1] = Length_UNKNOWN; tm2[2] = Length_2; @@ -497,8 +496,11 @@ static Variant() /// The variant type name or the string "unknown variant type" public static String GetVariantName(long variantType) { - String name = (String)numberToName[variantType]; - return name != null ? name : "unknown variant type"; + if (!numberToName.TryGetValue(variantType, out string name)) + { + return "unknown variant type"; + } + return name; } /// @@ -512,11 +514,13 @@ public static String GetVariantName(long variantType) public static int GetVariantLength(long variantType) { long key = (int)variantType; - if (numberToLength.Contains(key)) + + if(!numberToLength.TryGetValue(key, out int value)) + { return -2; - long Length = (long)numberToLength[key]; - return Convert.ToInt32(Length); - } + } + return Convert.ToInt32((long) value); + } } } \ No newline at end of file diff --git a/main/HSSF/Extractor/EventBasedExcelExtractor.cs b/main/HSSF/Extractor/EventBasedExcelExtractor.cs index 64c1c528a..f7e67f686 100644 --- a/main/HSSF/Extractor/EventBasedExcelExtractor.cs +++ b/main/HSSF/Extractor/EventBasedExcelExtractor.cs @@ -18,9 +18,8 @@ limitations under the License. namespace NPOI.HSSF.Extractor { using System; + using System.Collections.Generic; using System.Text; - using System.IO; - using System.Collections; using NPOI.HSSF.UserModel; using NPOI.HSSF.Record; @@ -160,7 +159,7 @@ private sealed class TextListener : IHSSFListener public FormatTrackingHSSFListener ft; private SSTRecord sstRecord; - private IList sheetNames = new ArrayList(); + private List sheetNames = []; public StringBuilder text = new StringBuilder(); private int sheetNum = -1; private int rowNum; diff --git a/main/HSSF/Model/DrawingManager2.cs b/main/HSSF/Model/DrawingManager2.cs index 9618098d8..6f68b5882 100644 --- a/main/HSSF/Model/DrawingManager2.cs +++ b/main/HSSF/Model/DrawingManager2.cs @@ -15,11 +15,12 @@ the License. You may obtain a copy of the License at limitations Under the License. ==================================================================== */ +using System.Collections.Generic; + +using NPOI.DDF; + namespace NPOI.HSSF.Model { - using NPOI.DDF; - using System.Collections; - /// /// Provides utilities to manage drawing Groups. /// @@ -28,8 +29,8 @@ namespace NPOI.HSSF.Model /// public class DrawingManager2 { - EscherDggRecord dgg; - IList drawingGroups = new ArrayList(); + private readonly EscherDggRecord dgg; + private readonly List drawingGroups = []; public DrawingManager2(EscherDggRecord dgg) diff --git a/main/HSSF/Model/HSSFFormulaParser.cs b/main/HSSF/Model/HSSFFormulaParser.cs index b332bef56..cba5bedf4 100644 --- a/main/HSSF/Model/HSSFFormulaParser.cs +++ b/main/HSSF/Model/HSSFFormulaParser.cs @@ -32,7 +32,7 @@ namespace NPOI.HSSF.Model public class HSSFFormulaParser { - private static IFormulaParsingWorkbook CreateParsingWorkbook(HSSFWorkbook book) + private static HSSFEvaluationWorkbook CreateParsingWorkbook(HSSFWorkbook book) { return HSSFEvaluationWorkbook.Create(book); } diff --git a/main/HSSF/Model/InternalSheet.cs b/main/HSSF/Model/InternalSheet.cs index e4c67e85c..b4da517ba 100644 --- a/main/HSSF/Model/InternalSheet.cs +++ b/main/HSSF/Model/InternalSheet.cs @@ -20,7 +20,7 @@ namespace NPOI.HSSF.Model using System; using System.Collections; using System.Collections.Generic; - using System.Text; + using NPOI.HSSF.Record; using NPOI.HSSF.Record.Aggregates; using NPOI.SS.Formula; @@ -461,9 +461,12 @@ public void VisitRecord(Record r) { _records.Add(r); } } - private static void SpillAggregate(RecordAggregate ra, List recs) { + + private static void SpillAggregate(ChartSubstreamRecordAggregate ra, List recs) + { ra.VisitContainedRecords(new RecordVisitor1(recs)); } + /// /// Creates a sheet with all the usual records minus values and the "index" /// record (not required). Sets the location pointer to where the first value @@ -2079,14 +2082,16 @@ public void Preserialize() */ public void ShiftBreaks(PageBreakRecord breaks, short start, short stop, int count) { - if (rowBreaks == null) + { return; - IEnumerator iterator = breaks.GetBreaksEnumerator(); - IList ShiftedBreak = new ArrayList(); + } + + IEnumerator iterator = breaks.GetBreaksEnumerator(); + List ShiftedBreak = []; while (iterator.MoveNext()) { - PageBreakRecord.Break breakItem = (PageBreakRecord.Break)iterator.Current; + PageBreakRecord.Break breakItem = iterator.Current; int breakLocation = breakItem.main; bool inStart = (breakLocation >= start); bool inEnd = (breakLocation <= stop); @@ -2097,7 +2102,7 @@ public void ShiftBreaks(PageBreakRecord breaks, short start, short stop, int cou iterator = ShiftedBreak.GetEnumerator(); while (iterator.MoveNext()) { - PageBreakRecord.Break breakItem = (PageBreakRecord.Break)iterator.Current; + PageBreakRecord.Break breakItem = iterator.Current; breaks.RemoveBreak(breakItem.main); breaks.AddBreak(breakItem.main + count, breakItem.subFrom, breakItem.subTo); } diff --git a/main/HSSF/Model/InternalWorkbook.cs b/main/HSSF/Model/InternalWorkbook.cs index 9e8ab66fa..7d2c131b4 100644 --- a/main/HSSF/Model/InternalWorkbook.cs +++ b/main/HSSF/Model/InternalWorkbook.cs @@ -1261,7 +1261,7 @@ public int Size * @return record containing a BOFRecord */ - private static Record CreateBOF() + private static BOFRecord CreateBOF() { BOFRecord retval = new BOFRecord(); @@ -1299,7 +1299,7 @@ protected Record CreateInterfaceHdr() * @return record containing a MMSRecord */ - private static Record CreateMMS() + private static MMSRecord CreateMMS() { MMSRecord retval = new MMSRecord(); @@ -1328,7 +1328,7 @@ protected Record CreateInterfaceEnd() * @return record containing a WriteAccessRecord */ - private static Record CreateWriteAccess() + private static WriteAccessRecord CreateWriteAccess() { WriteAccessRecord retval = new WriteAccessRecord(); String defaultUserName = "NPOI"; @@ -1356,7 +1356,7 @@ private static Record CreateWriteAccess() * @return record containing a CodepageRecord */ - private static Record CreateCodepage() + private static CodepageRecord CreateCodepage() { CodepageRecord retval = new CodepageRecord(); @@ -1371,7 +1371,7 @@ private static Record CreateCodepage() * @return record containing a DSFRecord */ - private static Record CreateDSF() + private static DSFRecord CreateDSF() { return new DSFRecord(false); // we don't even support double stream files } @@ -1383,15 +1383,10 @@ private static Record CreateDSF() * @see org.apache.poi.hssf.record.Record * @return record containing a TabIdRecord */ - - private static Record CreateTabId() + private static TabIdRecord CreateTabId() { - TabIdRecord retval = new TabIdRecord(); - short[] tabidarray = { - 0 - }; - - retval.SetTabIdArray(tabidarray); + TabIdRecord retval = new(); + retval.SetTabIdArray([0]); return retval; } @@ -1402,12 +1397,12 @@ private static Record CreateTabId() * @return record containing a FnGroupCountRecord */ - private static Record CreateFnGroupCount() + private static FnGroupCountRecord CreateFnGroupCount() { - FnGroupCountRecord retval = new FnGroupCountRecord(); - - retval.Count=(short)14; - return retval; + return new FnGroupCountRecord + { + Count = 14 + }; } /** @@ -1417,7 +1412,7 @@ private static Record CreateFnGroupCount() * @return record containing a WindowProtectRecord */ - private static Record CreateWindowProtect() + private static WindowProtectRecord CreateWindowProtect() { // by default even when we support it we won't // want it to be protected @@ -1443,7 +1438,7 @@ private static ProtectRecord CreateProtect() * @return record containing a PasswordRecord */ - private static Record CreatePassword() + private static PasswordRecord CreatePassword() { return new PasswordRecord(0x0000); // no password by default! } @@ -1467,7 +1462,7 @@ private static ProtectionRev4Record CreateProtectionRev4() * @return record containing a PasswordRev4Record */ - private static Record CreatePasswordRev4() + private static PasswordRev4Record CreatePasswordRev4() { return new PasswordRev4Record(0x0000); } @@ -1488,7 +1483,7 @@ private static Record CreatePasswordRev4() * @return record containing a WindowOneRecord */ - private static Record CreateWindowOne() + private static WindowOneRecord CreateWindowOne() { WindowOneRecord retval = new WindowOneRecord(); @@ -1511,7 +1506,7 @@ private static Record CreateWindowOne() * @return record containing a BackupRecord */ - private static Record CreateBackup() + private static BackupRecord CreateBackup() { BackupRecord retval = new BackupRecord(); @@ -1526,7 +1521,7 @@ private static Record CreateBackup() * @return record containing a HideObjRecord */ - private static Record CreateHideObj() + private static HideObjRecord CreateHideObj() { HideObjRecord retval = new HideObjRecord(); @@ -1541,7 +1536,7 @@ private static Record CreateHideObj() * @return record containing a DateWindow1904Record */ - private static Record CreateDateWindow1904() + private static DateWindow1904Record CreateDateWindow1904() { DateWindow1904Record retval = new DateWindow1904Record(); @@ -1556,7 +1551,7 @@ private static Record CreateDateWindow1904() * @return record containing a PrecisionRecord */ - private static Record CreatePrecision() + private static PrecisionRecord CreatePrecision() { PrecisionRecord retval = new PrecisionRecord(); @@ -1571,7 +1566,7 @@ private static Record CreatePrecision() * @return record containing a RefreshAllRecord */ - private static Record CreateRefreshAll() + private static RefreshAllRecord CreateRefreshAll() { return new RefreshAllRecord(false); } @@ -1583,12 +1578,12 @@ private static Record CreateRefreshAll() * @return record containing a BookBoolRecord */ - private static Record CreateBookBool() + private static BookBoolRecord CreateBookBool() { - BookBoolRecord retval = new BookBoolRecord(); - - retval.SaveLinkValues=(short)0; - return retval; + return new BookBoolRecord + { + SaveLinkValues = 0 + }; } /** @@ -1605,7 +1600,7 @@ private static Record CreateBookBool() * @return record containing a FontRecord */ - private static Record CreateFont() + private static FontRecord CreateFont() { FontRecord retval = new FontRecord(); @@ -1699,7 +1694,7 @@ private static Record CreateFont() * @see org.apache.poi.hssf.record.Record */ - private static Record CreateExtendedFormat(int id) + private static ExtendedFormatRecord CreateExtendedFormat(int id) { // we'll need multiple editions ExtendedFormatRecord retval = new ExtendedFormatRecord(); @@ -2090,7 +2085,7 @@ public StyleRecord CreateStyleRecord(int xfIndex) { * @see org.apache.poi.hssf.record.Record */ - private static Record CreateStyle(int id) + private static StyleRecord CreateStyle(int id) { // we'll need multiple editions StyleRecord retval = new StyleRecord(); @@ -2169,7 +2164,7 @@ private static UseSelFSRecord CreateUseSelFS() * @see org.apache.poi.hssf.record.Record */ - private static Record CreateBoundSheet(int id) + private static BoundSheetRecord CreateBoundSheet(int id) { return new BoundSheetRecord("Sheet" + (id + 1)); } @@ -2182,8 +2177,9 @@ private static Record CreateBoundSheet(int id) * @see org.apache.poi.hssf.record.Record */ - private static Record CreateCountry() - { // what a novel idea, Create your own! + private static CountryRecord CreateCountry() + { + // what a novel idea, Create your own! CountryRecord retval = new CountryRecord(); retval.DefaultCountry=((short)1); @@ -2211,12 +2207,12 @@ private static Record CreateCountry() * @see org.apache.poi.hssf.record.Record */ - private static Record CreateExtendedSST() + private static ExtSSTRecord CreateExtendedSST() { - ExtSSTRecord retval = new ExtSSTRecord(); - - retval.NumStringsPerBucket=((short)0x8); - return retval; + return new ExtSSTRecord + { + NumStringsPerBucket = 0x8 + }; } /** diff --git a/main/HSSF/Model/LinkTable.cs b/main/HSSF/Model/LinkTable.cs index 426fcfa78..474e0e107 100644 --- a/main/HSSF/Model/LinkTable.cs +++ b/main/HSSF/Model/LinkTable.cs @@ -321,12 +321,8 @@ public int RecordCount public NameRecord GetSpecificBuiltinRecord(byte builtInCode, int sheetNumber) { - - IEnumerator iterator = _definedNames.GetEnumerator(); - while (iterator.MoveNext()) + foreach (var record in _definedNames) { - NameRecord record = iterator.Current; - //print areas are one based if (record.BuiltInName == builtInCode && record.SheetNumber == sheetNumber) { diff --git a/main/HSSF/Record/AbstractEscherHolderRecord.cs b/main/HSSF/Record/AbstractEscherHolderRecord.cs index 13f9d0151..f36ee7801 100644 --- a/main/HSSF/Record/AbstractEscherHolderRecord.cs +++ b/main/HSSF/Record/AbstractEscherHolderRecord.cs @@ -91,7 +91,7 @@ protected void ConvertRawBytesToEscherRecords() private void ConvertToEscherRecords(int offset, int size, byte[] data) { escherRecords.Clear(); - IEscherRecordFactory recordFactory = new DefaultEscherRecordFactory(); + DefaultEscherRecordFactory recordFactory = new(); int pos = offset; while (pos < offset + size) { diff --git a/main/HSSF/Record/Aggregates/ConditionalFormattingTable.cs b/main/HSSF/Record/Aggregates/ConditionalFormattingTable.cs index 5cc18b757..465e82817 100644 --- a/main/HSSF/Record/Aggregates/ConditionalFormattingTable.cs +++ b/main/HSSF/Record/Aggregates/ConditionalFormattingTable.cs @@ -36,7 +36,7 @@ namespace NPOI.HSSF.Record.Aggregates public class ConditionalFormattingTable : RecordAggregate { - private readonly IList _cfHeaders; + private readonly List _cfHeaders; /** * Creates an empty ConditionalFormattingTable diff --git a/main/HSSF/Record/Aggregates/DataValidityTable.cs b/main/HSSF/Record/Aggregates/DataValidityTable.cs index 19ce4e701..d623a895e 100644 --- a/main/HSSF/Record/Aggregates/DataValidityTable.cs +++ b/main/HSSF/Record/Aggregates/DataValidityTable.cs @@ -15,13 +15,12 @@ the License. You may obtain a copy of the License at limitations under the License. ==================================================================== */ -namespace NPOI.HSSF.Record.Aggregates -{ - using System.Collections; +using System.Collections.Generic; - using NPOI.HSSF.Model; - using NPOI.HSSF.Record; +using NPOI.HSSF.Model; +namespace NPOI.HSSF.Record.Aggregates +{ /// /// Manages the DVALRecord and DVRecords for a single sheet /// See OOO excelfileformat.pdf section 4.14 @@ -35,15 +34,15 @@ public class DataValidityTable : RecordAggregate * The list of data validations for the current sheet. * Note - this may be empty (contrary to OOO documentation) */ - private readonly IList _validationList; + private readonly List _validationList; public DataValidityTable(RecordStream rs) { _headerRec = (DVALRecord)rs.GetNext(); - IList temp = new ArrayList(); + List temp = new(); while (rs.PeekNextClass() == typeof(DVRecord)) { - temp.Add(rs.GetNext()); + temp.Add((DVRecord) rs.GetNext()); } _validationList = temp; } @@ -51,7 +50,7 @@ public DataValidityTable(RecordStream rs) public DataValidityTable() { _headerRec = new DVALRecord(); - _validationList = new ArrayList(); + _validationList = new List(); } public override void VisitContainedRecords(RecordVisitor rv) diff --git a/main/HSSF/Record/Aggregates/PageSettingsBlock.cs b/main/HSSF/Record/Aggregates/PageSettingsBlock.cs index 1852184a8..513b77552 100644 --- a/main/HSSF/Record/Aggregates/PageSettingsBlock.cs +++ b/main/HSSF/Record/Aggregates/PageSettingsBlock.cs @@ -468,27 +468,28 @@ public void SetMargin(MarginType margin, double size) * @param stop Ending "main" value to shift breaks * @param count number of units (rows/columns) to shift by */ - private static void ShiftBreaks(PageBreakRecord breaks, int start, int stop, int count) { - - IEnumerator iterator = breaks.GetBreaksEnumerator(); - IList shiftedBreak = new ArrayList(); - while(iterator.MoveNext()) - { - PageBreakRecord.Break breakItem = (PageBreakRecord.Break)iterator.Current; - int breakLocation = breakItem.main; - bool inStart = (breakLocation >= start); - bool inEnd = (breakLocation <= stop); - if(inStart && inEnd) - shiftedBreak.Add(breakItem); - } - - iterator = shiftedBreak.GetEnumerator(); - while (iterator.MoveNext()) { - PageBreakRecord.Break breakItem = (PageBreakRecord.Break)iterator.Current; - breaks.RemoveBreak(breakItem.main); - breaks.AddBreak((short)(breakItem.main+count), breakItem.subFrom, breakItem.subTo); - } - } + private static void ShiftBreaks(PageBreakRecord breaks, int start, int stop, int count) + { + IEnumerator iterator = breaks.GetBreaksEnumerator(); + List shiftedBreak = []; + while(iterator.MoveNext()) + { + PageBreakRecord.Break breakItem = (PageBreakRecord.Break) iterator.Current; + int breakLocation = breakItem.main; + bool inStart = (breakLocation >= start); + bool inEnd = (breakLocation <= stop); + if(inStart && inEnd) + shiftedBreak.Add(breakItem); + } + + iterator = shiftedBreak.GetEnumerator(); + while(iterator.MoveNext()) + { + PageBreakRecord.Break breakItem = (PageBreakRecord.Break) iterator.Current; + breaks.RemoveBreak(breakItem.main); + breaks.AddBreak((short) (breakItem.main + count), breakItem.subFrom, breakItem.subTo); + } + } /** diff --git a/main/HSSF/Record/Crypto/Biff8EncryptionKey.cs b/main/HSSF/Record/Crypto/Biff8EncryptionKey.cs index b87c625df..0829e80df 100644 --- a/main/HSSF/Record/Crypto/Biff8EncryptionKey.cs +++ b/main/HSSF/Record/Crypto/Biff8EncryptionKey.cs @@ -50,30 +50,27 @@ internal static byte[] CreateKeyDigest(String password, byte[] docIdData) passwordData[i * 2 + 1] = (byte)((ch << 8) & 0xFF); } - byte[] kd; - using (MD5 md5 = new MD5CryptoServiceProvider()) - { - byte[] passwordHash = md5.ComputeHash(passwordData); + using MD5CryptoServiceProvider md5 = new(); + byte[] passwordHash = md5.ComputeHash(passwordData); - md5.Initialize(); + md5.Initialize(); - byte[] data = new byte[PASSWORD_HASH_NUMBER_OF_BYTES_USED * 16 + docIdData.Length * 16]; + byte[] data = new byte[PASSWORD_HASH_NUMBER_OF_BYTES_USED * 16 + docIdData.Length * 16]; - int offset = 0; - for (int i = 0; i < 16; i++) - { - Array.Copy(passwordHash, 0, data, offset, PASSWORD_HASH_NUMBER_OF_BYTES_USED); - offset += PASSWORD_HASH_NUMBER_OF_BYTES_USED;// passwordHash.Length; - Array.Copy(docIdData, 0, data, offset, docIdData.Length); - offset += docIdData.Length; - } - kd = md5.ComputeHash(data); - byte[] result = new byte[KEY_DIGEST_LENGTH]; - Array.Copy(kd, 0, result, 0, KEY_DIGEST_LENGTH); - md5.Clear(); - - return result; + int offset = 0; + for (int i = 0; i < 16; i++) + { + Array.Copy(passwordHash, 0, data, offset, PASSWORD_HASH_NUMBER_OF_BYTES_USED); + offset += PASSWORD_HASH_NUMBER_OF_BYTES_USED;// passwordHash.Length; + Array.Copy(docIdData, 0, data, offset, docIdData.Length); + offset += docIdData.Length; } + byte[] kd = md5.ComputeHash(data); + byte[] result = new byte[KEY_DIGEST_LENGTH]; + Array.Copy(kd, 0, result, 0, KEY_DIGEST_LENGTH); + md5.Clear(); + + return result; } /** diff --git a/main/HSSF/Record/EmbeddedObjectRefSubRecord.cs b/main/HSSF/Record/EmbeddedObjectRefSubRecord.cs index 855541685..e65ed7a48 100644 --- a/main/HSSF/Record/EmbeddedObjectRefSubRecord.cs +++ b/main/HSSF/Record/EmbeddedObjectRefSubRecord.cs @@ -183,19 +183,17 @@ public override short Sid private static Ptg ReadRefPtg(byte[] formulaRawBytes) { - using (MemoryStream ms = RecyclableMemory.GetStream(formulaRawBytes)) + using MemoryStream ms = RecyclableMemory.GetStream(formulaRawBytes); + LittleEndianInputStream in1 = new LittleEndianInputStream(ms); + byte ptgSid = (byte)in1.ReadByte(); + switch (ptgSid) { - ILittleEndianInput in1 = new LittleEndianInputStream(ms); - byte ptgSid = (byte)in1.ReadByte(); - switch (ptgSid) - { - case AreaPtg.sid: return new AreaPtg(in1); - case Area3DPtg.sid: return new Area3DPtg(in1); - case RefPtg.sid: return new RefPtg(in1); - case Ref3DPtg.sid: return new Ref3DPtg(in1); - } - return null; + case AreaPtg.sid: return new AreaPtg(in1); + case Area3DPtg.sid: return new Area3DPtg(in1); + case RefPtg.sid: return new RefPtg(in1); + case Ref3DPtg.sid: return new Ref3DPtg(in1); } + return null; } private static byte[] ReadRawData(ILittleEndianInput in1, int size) diff --git a/main/HSSF/Record/EscherAggregate.cs b/main/HSSF/Record/EscherAggregate.cs index 808c71d16..5a8055f93 100644 --- a/main/HSSF/Record/EscherAggregate.cs +++ b/main/HSSF/Record/EscherAggregate.cs @@ -432,8 +432,8 @@ public static EscherAggregate CreateAggregate(List records, int locF { // Keep track of any shape records Created so we can match them back to the object id's. // Textbox objects are also treated as shape objects. - List shapeRecords = new List(); - IEscherRecordFactory recordFactory = new CustomEscherRecordFactory(shapeRecords); + List shapeRecords = []; + CustomEscherRecordFactory recordFactory = new(shapeRecords); // Create one big buffer using (MemoryStream stream = RecyclableMemory.GetStream()) diff --git a/main/HSSF/Record/ExternSheetRecord.cs b/main/HSSF/Record/ExternSheetRecord.cs index 1e332b685..6d1ba56f0 100644 --- a/main/HSSF/Record/ExternSheetRecord.cs +++ b/main/HSSF/Record/ExternSheetRecord.cs @@ -16,17 +16,14 @@ the License. You may obtain a copy of the License at limitations Under the License. ==================================================================== */ +using System; +using System.Text; +using System.Collections.Generic; + +using NPOI.Util; namespace NPOI.HSSF.Record { - - using System; - using System.Text; - using System.Collections; - using NPOI.Util; - using System.Collections.Generic; - - public class RefSubRecord { public const int ENCODED_SIZE = 6; @@ -114,14 +111,11 @@ public void Serialize(ILittleEndianOutput out1) public class ExternSheetRecord : StandardRecord { public const short sid = 0x17; - private readonly IList _list; - - - + private readonly List _list; public ExternSheetRecord() { - _list = new List(); + _list = []; } /** diff --git a/main/HSSF/Record/HyperlinkRecord.cs b/main/HSSF/Record/HyperlinkRecord.cs index 666ab84dc..9166a52f6 100644 --- a/main/HSSF/Record/HyperlinkRecord.cs +++ b/main/HSSF/Record/HyperlinkRecord.cs @@ -232,7 +232,8 @@ public HyperlinkRecord(RecordInputStream in1) Console.WriteLine(HexDump.ToHex(in1.ReadRemainder())); } } - private static byte[] ReadTail(byte[] expectedTail, ILittleEndianInput in1) + + private static byte[] ReadTail(byte[] expectedTail, RecordInputStream in1) { byte[] result = new byte[TAIL_SIZE]; in1.ReadFully(result); @@ -249,6 +250,7 @@ private static byte[] ReadTail(byte[] expectedTail, ILittleEndianInput in1) //} return result; } + private static void WriteTail(byte[] tail, ILittleEndianOutput out1) { out1.Write(tail); diff --git a/main/HSSF/Record/LbsDataSubRecord.cs b/main/HSSF/Record/LbsDataSubRecord.cs index 5379bbd1b..ab7c1c957 100644 --- a/main/HSSF/Record/LbsDataSubRecord.cs +++ b/main/HSSF/Record/LbsDataSubRecord.cs @@ -269,16 +269,16 @@ public override void Serialize(ILittleEndianOutput out1) } private static Ptg ReadRefPtg(byte[] formulaRawBytes) { - ILittleEndianInput in1 = new LittleEndianByteArrayInputStream(formulaRawBytes); + LittleEndianByteArrayInputStream in1 = new(formulaRawBytes); byte ptgSid = (byte)in1.ReadByte(); - switch (ptgSid) + return ptgSid switch { - case AreaPtg.sid: return new AreaPtg(in1); - case Area3DPtg.sid: return new Area3DPtg(in1); - case RefPtg.sid: return new RefPtg(in1); - case Ref3DPtg.sid: return new Ref3DPtg(in1); - } - return null; + AreaPtg.sid => new AreaPtg(in1), + Area3DPtg.sid => new Area3DPtg(in1), + RefPtg.sid => new RefPtg(in1), + Ref3DPtg.sid => new Ref3DPtg(in1), + _ => null + }; } public override Object Clone() { diff --git a/main/HSSF/Record/NameCommentRecord.cs b/main/HSSF/Record/NameCommentRecord.cs index 1d43e1aad..885b0991d 100644 --- a/main/HSSF/Record/NameCommentRecord.cs +++ b/main/HSSF/Record/NameCommentRecord.cs @@ -103,7 +103,7 @@ protected override int DataSize */ public NameCommentRecord(RecordInputStream ris) { - ILittleEndianInput in1 = ris; + RecordInputStream in1 = ris; field_1_record_type = in1.ReadShort(); field_2_frt_cell_ref_flag = in1.ReadShort(); field_3_reserved = in1.ReadLong(); diff --git a/main/HSSF/Record/NameRecord.cs b/main/HSSF/Record/NameRecord.cs index 022ca761a..687cfeceb 100644 --- a/main/HSSF/Record/NameRecord.cs +++ b/main/HSSF/Record/NameRecord.cs @@ -170,7 +170,7 @@ protected int DataSize public NameRecord(RecordInputStream ris) { byte[] remainder = ris.ReadAllContinuedRemainder(); - ILittleEndianInput in1 = new LittleEndianByteArrayInputStream(remainder); + LittleEndianByteArrayInputStream in1 = new LittleEndianByteArrayInputStream(remainder); field_1_option_flag = in1.ReadShort(); field_2_keyboard_shortcut = (byte)in1.ReadByte(); int field_3_length_name_text = in1.ReadByte(); @@ -545,7 +545,7 @@ public int ExternSheetNumber } - private static Ptg CreateNewPtg() + private static Area3DPtg CreateNewPtg() { return new Area3DPtg("A1:A1", 0); // TODO - change to not be partially initialised } diff --git a/main/HSSF/UserModel/EvaluationCycleDetector.cs b/main/HSSF/UserModel/EvaluationCycleDetector.cs index de058d38d..ca2b7ba02 100644 --- a/main/HSSF/UserModel/EvaluationCycleDetector.cs +++ b/main/HSSF/UserModel/EvaluationCycleDetector.cs @@ -106,7 +106,7 @@ public override String ToString() } } - private readonly IList _evaluationFrames; + private readonly ArrayList _evaluationFrames; public EvaluationCycleDetector() { diff --git a/main/HSSF/UserModel/HSSFCell.cs b/main/HSSF/UserModel/HSSFCell.cs index c600711db..428d4297e 100644 --- a/main/HSSF/UserModel/HSSFCell.cs +++ b/main/HSSF/UserModel/HSSFCell.cs @@ -19,7 +19,6 @@ limitations Under the License. namespace NPOI.HSSF.UserModel { using System; - using System.Collections; using System.IO; using NPOI.HSSF.Model; using NPOI.HSSF.Record; @@ -31,7 +30,6 @@ namespace NPOI.HSSF.UserModel using NPOI.SS.Formula; using System.Globalization; using System.Collections.Generic; - using NPOI.Util; using NPOI.SS.Formula.Eval; /// @@ -831,7 +829,7 @@ private static String GetCellTypeName(CellType cellTypeCode) /// The actual type code. /// if set to true [is formula cell]. /// - private static Exception TypeMismatch(CellType expectedTypeCode, CellType actualTypeCode, bool isFormulaCell) + private static InvalidOperationException TypeMismatch(CellType expectedTypeCode, CellType actualTypeCode, bool isFormulaCell) { String msg = "Cannot get a " + HSSFCell.GetCellTypeName(expectedTypeCode) + " value from a " @@ -1358,9 +1356,8 @@ public IHyperlink Hyperlink public void RemoveHyperlink() { RecordBase toRemove = null; - for (IEnumerator it = _sheet.Sheet.Records.GetEnumerator(); it.MoveNext(); ) + foreach (var rec in _sheet.Sheet.Records) { - RecordBase rec = it.Current; if (rec is HyperlinkRecord link) { if (link.FirstColumn == _record.Column && link.FirstRow == _record.Row) diff --git a/main/HSSF/UserModel/HSSFChart.cs b/main/HSSF/UserModel/HSSFChart.cs index d2225cc12..935b4821f 100644 --- a/main/HSSF/UserModel/HSSFChart.cs +++ b/main/HSSF/UserModel/HSSFChart.cs @@ -1108,7 +1108,7 @@ public SeriesRecord GetSeries() return series; } - private static CellRangeAddressBase GetCellRange(LinkedDataRecord linkedDataRecord) + private static CellRangeAddress GetCellRange(LinkedDataRecord linkedDataRecord) { if (linkedDataRecord == null) { diff --git a/main/HSSF/UserModel/HSSFRichTextString.cs b/main/HSSF/UserModel/HSSFRichTextString.cs index 264a0d6c6..c42990613 100644 --- a/main/HSSF/UserModel/HSSFRichTextString.cs +++ b/main/HSSF/UserModel/HSSFRichTextString.cs @@ -15,15 +15,14 @@ the License. You may obtain a copy of the License at limitations Under the License. ==================================================================== */ -namespace NPOI.HSSF.UserModel -{ - using System; - using System.Collections; +using System; +using System.Collections.Generic; - using NPOI.HSSF.Record; - using NPOI.HSSF.Model; - using System.Collections.Generic; +using NPOI.HSSF.Record; +using NPOI.HSSF.Model; +namespace NPOI.HSSF.UserModel +{ /// /// Rich text Unicode string. These strings can have fonts applied to /// arbitary parts of the string. @@ -145,15 +144,13 @@ public void ApplyFont(int startIndex, int endIndex, short fontIndex) //Need to clear the current formatting between the startIndex and endIndex _string = CloneStringIfRequired(); - System.Collections.Generic.List formatting = _string.FormatIterator(); + List formatting = _string.FormatIterator(); - ArrayList deletedFR = new ArrayList(); + List deletedFR = []; if (formatting != null) { - IEnumerator formats = formatting.GetEnumerator(); - while (formats.MoveNext()) + foreach (var r in formatting) { - UnicodeString.FormatRun r = formats.Current; if ((r.CharacterPos >= startIndex) && (r.CharacterPos < endIndex)) { deletedFR.Add(r); diff --git a/main/HSSF/UserModel/HSSFShapeGroup.cs b/main/HSSF/UserModel/HSSFShapeGroup.cs index 127212cbb..e54b78251 100644 --- a/main/HSSF/UserModel/HSSFShapeGroup.cs +++ b/main/HSSF/UserModel/HSSFShapeGroup.cs @@ -387,7 +387,7 @@ internal override HSSFShape CloneShape() throw new NotImplementedException("Use method cloneShape(HSSFPatriarch patriarch)"); } - internal HSSFShape CloneShape(HSSFPatriarch patriarch) + internal HSSFShapeGroup CloneShape(HSSFPatriarch patriarch) { EscherContainerRecord spgrContainer = new EscherContainerRecord(); spgrContainer.RecordId = (EscherContainerRecord.SPGR_CONTAINER); diff --git a/main/HSSF/UserModel/HSSFSheet.cs b/main/HSSF/UserModel/HSSFSheet.cs index 1d26b92ab..0976a71ae 100644 --- a/main/HSSF/UserModel/HSSFSheet.cs +++ b/main/HSSF/UserModel/HSSFSheet.cs @@ -15,13 +15,13 @@ the License. You may obtain a copy of the License at limitations Under the License. ==================================================================== */ -using System.Collections.ObjectModel; - namespace NPOI.HSSF.UserModel { using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; + using NPOI.DDF; using NPOI.HSSF.Model; using NPOI.HSSF.Record; @@ -33,13 +33,10 @@ namespace NPOI.HSSF.UserModel using NPOI.SS.Formula.PTG; using NPOI.SS.UserModel; using NPOI.SS.Util; - using System.Globalization; - using NPOI.Util; using NPOI.SS.UserModel.Helpers; using NPOI.HSSF.UserModel.helpers; - using SixLabors.Fonts; - + using SixLabors.Fonts; /// /// High level representation of a worksheet. @@ -2243,7 +2240,7 @@ public ICellRange RemoveArrayFormula(ICell cell) /// /// Also creates cells if they don't exist. /// - private ICellRange GetCellRange(CellRangeAddress range) + private SSCellRange GetCellRange(CellRangeAddress range) { int firstRow = range.FirstRow; int firstColumn = range.FirstColumn; @@ -2283,7 +2280,7 @@ public ICellRange SetArrayFormula(String formula, CellRangeAddress range) // make sure the formula parses OK first int sheetIndex = _workbook.GetSheetIndex(this); Ptg[] ptgs = HSSFFormulaParser.Parse(formula, _workbook, FormulaType.Array, sheetIndex); - ICellRange cells = GetCellRange(range); + SSCellRange cells = GetCellRange(range); foreach (HSSFCell c in cells) { @@ -2631,14 +2628,14 @@ public IList DVRecords { get { - IList dvRecords = new ArrayList(); - IList records = _sheet.Records; + List dvRecords = []; + List records = _sheet.Records; for (int index = 0; index < records.Count; index++) { - if (records[index] is DVRecord) + if (records[index] is DVRecord dvRecord) { - dvRecords.Add(records[index]); + dvRecords.Add(dvRecord); } } return dvRecords; diff --git a/main/HSSF/UserModel/HSSFWorkbook.cs b/main/HSSF/UserModel/HSSFWorkbook.cs index 1080d2979..1e89fb99b 100644 --- a/main/HSSF/UserModel/HSSFWorkbook.cs +++ b/main/HSSF/UserModel/HSSFWorkbook.cs @@ -614,7 +614,7 @@ public void SetSelectedTabs(IList indexes) ValidateSheetIndex(index); } // ignore duplicates - ISet set = new HashSet(indexes); + HashSet set = new(indexes); int nSheets = _sheets.Count; for (int i = 0; i < nSheets; i++) { diff --git a/main/POIFS/Crypt/Standard/StandardEncryptor.cs b/main/POIFS/Crypt/Standard/StandardEncryptor.cs index b57a2b5c4..2f3a93088 100644 --- a/main/POIFS/Crypt/Standard/StandardEncryptor.cs +++ b/main/POIFS/Crypt/Standard/StandardEncryptor.cs @@ -15,16 +15,15 @@ the License. You may obtain a copy of the License at limitations under the License. ==================================================================== */ +using System; +using System.IO; + +using NPOI.POIFS.EventFileSystem; +using NPOI.POIFS.FileSystem; +using NPOI.Util; + namespace NPOI.POIFS.Crypt.Standard { - using System; - using System.IO; - using System.Security.AccessControl; - using NPOI.POIFS.Crypt; - using NPOI.POIFS.EventFileSystem; - using NPOI.POIFS.FileSystem; - using NPOI.Util; - public class StandardEncryptor : Encryptor { private StandardEncryptionInfoBuilder builder; @@ -109,8 +108,8 @@ protected class StandardCipherOutputStream : ByteArrayOutputStream, POIFSWriterL protected long countBytes; protected FileInfo fileOut; protected DirectoryNode dir; - ByteArrayOutputStream out1; - FileStream rawStream;// maybe has memory leak problem. + private readonly CipherOutputStream out1; + private readonly FileStream rawStream;// maybe has memory leak problem. protected internal StandardCipherOutputStream(DirectoryNode dir, StandardEncryptor encryptor) { diff --git a/main/POIFS/FileSystem/OPOIFSFileSystem.cs b/main/POIFS/FileSystem/OPOIFSFileSystem.cs index f29f4e38b..bd5df06ae 100644 --- a/main/POIFS/FileSystem/OPOIFSFileSystem.cs +++ b/main/POIFS/FileSystem/OPOIFSFileSystem.cs @@ -67,7 +67,7 @@ public static Stream CreateNonClosingInputStream(Stream stream) { } private PropertyTable _property_table; - private IList _documents; + private List _documents; private DirectoryNode _root; /** * What big block size the file uses. Most files diff --git a/main/POIFS/Macros/VBAMacroReader.cs b/main/POIFS/Macros/VBAMacroReader.cs index fdc2b6e60..951d244cc 100644 --- a/main/POIFS/Macros/VBAMacroReader.cs +++ b/main/POIFS/Macros/VBAMacroReader.cs @@ -218,7 +218,7 @@ protected void FindMacros(DirectoryNode dir, ModuleMap modules) * @throws IOException */ - private static String ReadString(InputStream stream, int length, Encoding charset) + private static String ReadString(RLEDecompressingInputStream stream, int length, Encoding charset) { byte[] buffer = new byte[length]; int count = stream.Read(buffer); @@ -254,9 +254,8 @@ private static void ReadModule(RLEDecompressingInputStream in1, String streamNam else { // Decompress a previously found module and store the decompressed result into module.buf - InputStream stream = new RLEDecompressingInputStream( - new MemoryStream(module.buf, moduleOffset, module.buf.Length - moduleOffset) - ); + using MemoryStream memoryStream = new(module.buf, moduleOffset, module.buf.Length - moduleOffset); + using RLEDecompressingInputStream stream = new(memoryStream); module.Read(stream); stream.Close(); } @@ -287,7 +286,7 @@ private static void ReadModule(DocumentInputStream dis, String name, ModuleMap m { throw new IOException("tried to skip " + module.offset + " bytes, but actually skipped " + skippedBytes + " bytes"); } - InputStream stream = new RLEDecompressingInputStream(dis); + using RLEDecompressingInputStream stream = new(dis); module.Read(stream); stream.Close(); } @@ -299,7 +298,7 @@ private static void ReadModule(DocumentInputStream dis, String name, ModuleMap m * @throws IOException */ - private static void TrySkip(InputStream in1, long n) + private static void TrySkip(RLEDecompressingInputStream in1, long n) { long skippedBytes = in1.Skip(n); if (skippedBytes != n) diff --git a/main/POIFS/Storage/SmallBlockTableWriter.cs b/main/POIFS/Storage/SmallBlockTableWriter.cs index 17c58ddc9..44423fb1c 100644 --- a/main/POIFS/Storage/SmallBlockTableWriter.cs +++ b/main/POIFS/Storage/SmallBlockTableWriter.cs @@ -43,7 +43,7 @@ namespace NPOI.POIFS.Storage public class SmallBlockTableWriter : BlockWritable, BATManaged { private readonly BlockAllocationTableWriter _sbat; - private readonly IList _small_blocks; + private readonly List _small_blocks; private readonly int _big_block_count; private readonly RootProperty _root; diff --git a/main/SS/Format/CellDateFormatter.cs b/main/SS/Format/CellDateFormatter.cs index d34b16644..a1d3f21fe 100644 --- a/main/SS/Format/CellDateFormatter.cs +++ b/main/SS/Format/CellDateFormatter.cs @@ -33,15 +33,14 @@ public class CellDateFormatter : CellFormatter private bool amPmUpper; private bool ShowM; private bool ShowAmPm; - private readonly FormatBase dateFmt; + private readonly SimpleDateFormat dateFmt; private String sFmt; private int millisecondPartLength = 0; private static readonly TimeSpan EXCEL_EPOCH_TIME; private static readonly DateTime EXCEL_EPOCH_DATE; - private static readonly CellFormatter SIMPLE_DATE = new CellDateFormatter( - "mm/d/y"); + private static readonly CellDateFormatter SIMPLE_DATE = new CellDateFormatter("mm/d/y"); static CellDateFormatter() { diff --git a/main/SS/Format/CellNumberFormatter.cs b/main/SS/Format/CellNumberFormatter.cs index 7619e23ea..e3fc934f4 100644 --- a/main/SS/Format/CellNumberFormatter.cs +++ b/main/SS/Format/CellNumberFormatter.cs @@ -14,17 +14,16 @@ the License. You may obtain a copy of the License at See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ -namespace NPOI.SS.Format -{ - using System; - using System.Text.RegularExpressions; - using System.Text; - using System.Collections.Generic; - using NPOI.SS.Util; - using System.Collections; - using NPOI.Util; +using System; +using System.Text; +using System.Collections.Generic; +using NPOI.SS.Util; +using System.Collections; + +namespace NPOI.SS.Format +{ /** * This class : printing out a value using a number format. * @@ -56,9 +55,9 @@ public class CellNumberFormatter : CellFormatter private DecimalFormat decimalFmt; private static List EmptySpecialList = new List(); - private static readonly CellFormatter SIMPLE_NUMBER = new SimpleNumberCellFormatter("General"); - private static readonly CellFormatter SIMPLE_INT = new CellNumberFormatter("#"); - private static readonly CellFormatter SIMPLE_FLOAT = new CellNumberFormatter("#.#"); + private static readonly SimpleNumberCellFormatter SIMPLE_NUMBER = new SimpleNumberCellFormatter("General"); + private static readonly CellNumberFormatter SIMPLE_INT = new CellNumberFormatter("#"); + private static readonly CellNumberFormatter SIMPLE_FLOAT = new CellNumberFormatter("#.#"); /// /// The CellNumberFormatter.simpleValue() method uses the SIMPLE_NUMBER @@ -409,7 +408,7 @@ private List specialsFor(int pos, int takeFirst) { if (pos >= specials.Count) return EmptySpecialList; - IEnumerator it = specials.GetRange(pos + takeFirst, specials.Count - pos - takeFirst).GetEnumerator(); + List.Enumerator it = specials.GetRange(pos + takeFirst, specials.Count - pos - takeFirst).GetEnumerator(); //.ListIterator(pos + takeFirst); it.MoveNext(); Special last = it.Current; @@ -461,12 +460,8 @@ private static int interpretPrecision(Special decimalPoint, List specia if (idx != -1) { // skip over the decimal point itself - IEnumerator it = specials.GetRange(idx + 1, specials.Count - idx - 1).GetEnumerator();//.ListIterator(specials.IndexOf(decimalPoint)); - //if (it.HasNext()) - // it.Next(); // skip over the decimal point itself - while (it.MoveNext()) + foreach (Special s in specials.GetRange(idx + 1, specials.Count - idx - 1)) { - Special s = it.Current; if (!IsDigitFmt(s)) { break; @@ -524,12 +519,10 @@ private static bool interpretIntegerCommas(StringBuilder sb, List speci } // Now strip them out -- we only need their interpretation, not their presence - IEnumerator it = specials.GetEnumerator(); int Removed = 0; - List toRemove = new List(); - while (it.MoveNext()) + List toRemove = []; + foreach (var s in specials) { - Special s = it.Current; s.pos -= Removed; if (s.ch == ',') { @@ -797,7 +790,7 @@ private void WriteScientific(double value, StringBuilder output, SortedList it = exponentSpecials.GetEnumerator();//.ListIterator(1); + List.Enumerator it = exponentSpecials.GetEnumerator();//.ListIterator(1); it.MoveNext(); it.MoveNext(); Special expSign = it.Current;//.Next(); diff --git a/main/SS/Format/CellTextFormatter.cs b/main/SS/Format/CellTextFormatter.cs index 72473cee3..3c1d20071 100644 --- a/main/SS/Format/CellTextFormatter.cs +++ b/main/SS/Format/CellTextFormatter.cs @@ -28,10 +28,11 @@ namespace NPOI.SS.Format */ public class CellTextFormatter : CellFormatter { - private int[] textPos; - private String desc; + private readonly int[] textPos; + private readonly string desc; + + internal static readonly CellTextFormatter SIMPLE_TEXT = new CellTextFormatter("@"); - internal static CellFormatter SIMPLE_TEXT = new CellTextFormatter("@"); private sealed class PartHandler : CellFormatPart.IPartHandler { private int numplace; diff --git a/main/SS/Formula/CacheAreaEval.cs b/main/SS/Formula/CacheAreaEval.cs index 7adca315f..7bc206558 100644 --- a/main/SS/Formula/CacheAreaEval.cs +++ b/main/SS/Formula/CacheAreaEval.cs @@ -33,8 +33,7 @@ public override AreaEval Offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { - AreaI area = new OffsetArea(FirstRow, FirstColumn, - relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); + OffsetArea area = new(FirstRow, FirstColumn, relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); int height = area.LastRow - area.FirstRow + 1; int width = area.LastColumn - area.FirstColumn + 1; diff --git a/main/SS/Formula/CellEvaluationFrame.cs b/main/SS/Formula/CellEvaluationFrame.cs index 2d2c0387d..266c80e68 100644 --- a/main/SS/Formula/CellEvaluationFrame.cs +++ b/main/SS/Formula/CellEvaluationFrame.cs @@ -15,32 +15,31 @@ the License. You may obtain a copy of the License at limitations under the License. ==================================================================== */ -namespace NPOI.SS.Formula -{ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; - using System; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - using System.Text; - using NPOI.SS.Formula.Eval; +using NPOI.SS.Formula.Eval; +namespace NPOI.SS.Formula +{ /** * Stores details about the current evaluation of a cell.
*/ - class CellEvaluationFrame + internal sealed class CellEvaluationFrame { - private readonly FormulaCellCacheEntry _cce; - private readonly ISet _sensitiveInputCells; + private readonly HashSet _sensitiveInputCells; private FormulaUsedBlankCellSet _usedBlankCellGroup; public CellEvaluationFrame(FormulaCellCacheEntry cce) { _cce = cce; - _sensitiveInputCells = new HashSet(); + _sensitiveInputCells = []; } - public CellCacheEntry GetCCE() + + public FormulaCellCacheEntry GetCCE() { return _cce; } diff --git a/main/SS/Formula/Constant/ConstantValueParser.cs b/main/SS/Formula/Constant/ConstantValueParser.cs index ae3c9b3a3..3914fc4d4 100644 --- a/main/SS/Formula/Constant/ConstantValueParser.cs +++ b/main/SS/Formula/Constant/ConstantValueParser.cs @@ -81,7 +81,7 @@ private static object ReadAConstantValue(ILittleEndianInput in1) throw new Exception("Unknown grbit value (" + grbit + ")"); } - private static Object ReadBoolean(ILittleEndianInput in1) + private static bool ReadBoolean(ILittleEndianInput in1) { byte val = (byte)in1.ReadLong(); // 7 bytes 'not used' switch (val) diff --git a/main/SS/Formula/Eval/ConcatEval.cs b/main/SS/Formula/Eval/ConcatEval.cs index 3dfbde549..5f5d35a7c 100644 --- a/main/SS/Formula/Eval/ConcatEval.cs +++ b/main/SS/Formula/Eval/ConcatEval.cs @@ -54,7 +54,7 @@ public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEva return new StringEval(sb.ToString()); } - private static Object GetText(ValueEval ve) + private static string GetText(ValueEval ve) { if (ve is StringValueEval sve) { @@ -64,8 +64,7 @@ private static Object GetText(ValueEval ve) { return ""; } - throw new InvalidOperationException("Unexpected value type (" - + ve.GetType().Name + ")"); + throw new InvalidOperationException($"Unexpected value type ({ve.GetType().Name})"); } } } \ No newline at end of file diff --git a/main/SS/Formula/EvaluationTracker.cs b/main/SS/Formula/EvaluationTracker.cs index 1b13f7843..4a6fc899f 100644 --- a/main/SS/Formula/EvaluationTracker.cs +++ b/main/SS/Formula/EvaluationTracker.cs @@ -15,15 +15,13 @@ the License. You may obtain a copy of the License at limitations under the License. ==================================================================== */ -namespace NPOI.SS.Formula -{ +using System; +using System.Collections.Generic; - using System; - using System.Collections; - using System.Collections.Generic; - using NPOI.SS.Formula.Eval; - +using NPOI.SS.Formula.Eval; +namespace NPOI.SS.Formula +{ /// /// Instances of this class keep track of multiple dependent cell evaluations due /// To recursive calls To @@ -37,15 +35,15 @@ namespace NPOI.SS.Formula public class EvaluationTracker { // TODO - consider deleting this class and letting CellEvaluationFrame take care of itself - private readonly IList _evaluationFrames; - private readonly ISet _currentlyEvaluatingCells; + private readonly List _evaluationFrames; + private readonly HashSet _currentlyEvaluatingCells; private readonly EvaluationCache _cache; public EvaluationTracker(EvaluationCache cache) { _cache = cache; - _evaluationFrames = new List(); - _currentlyEvaluatingCells = new HashSet(); + _evaluationFrames = []; + _currentlyEvaluatingCells = []; } /** diff --git a/main/SS/Formula/FormulaCellCacheEntrySet.cs b/main/SS/Formula/FormulaCellCacheEntrySet.cs index c1ebfcb9f..df3f5dc09 100644 --- a/main/SS/Formula/FormulaCellCacheEntrySet.cs +++ b/main/SS/Formula/FormulaCellCacheEntrySet.cs @@ -125,7 +125,7 @@ private static bool AddInternal(CellCacheEntry[] arr, CellCacheEntry cce) throw new InvalidOperationException("No empty space found"); } - public bool Remove(CellCacheEntry cce) + public bool Remove(FormulaCellCacheEntry cce) { FormulaCellCacheEntry[] arr = _arr; diff --git a/main/SS/Formula/FormulaParser.cs b/main/SS/Formula/FormulaParser.cs index 9fbdecfdd..0e8a4ef85 100644 --- a/main/SS/Formula/FormulaParser.cs +++ b/main/SS/Formula/FormulaParser.cs @@ -200,7 +200,7 @@ private void GetChar() } /** Report What Was Expected */ - private Exception expected(String s) + private FormulaParseException expected(String s) { String msg; @@ -1518,7 +1518,7 @@ private SheetIdentifier ParseSheetName() * If we have something that looks like [book]Sheet1: or * Sheet1, see if it's actually a range eg Sheet1:Sheet2! */ - private SheetIdentifier ParseSheetRange(String bookname, NameIdentifier sheet1Name) + private SheetRangeIdentifier ParseSheetRange(String bookname, NameIdentifier sheet1Name) { GetChar(); SheetIdentifier sheet2 = ParseSheetName(); @@ -2316,7 +2316,7 @@ private ParseNode ComparisonExpression() } } - private Ptg GetComparisonToken() + private ValueOperatorPtg GetComparisonToken() { if (look == '=') { diff --git a/main/SS/Formula/FormulaShifter.cs b/main/SS/Formula/FormulaShifter.cs index 16bcc2663..d421de740 100644 --- a/main/SS/Formula/FormulaShifter.cs +++ b/main/SS/Formula/FormulaShifter.cs @@ -15,13 +15,14 @@ the License. You may obtain a copy of the License at limitations under the License. ==================================================================== */ -namespace NPOI.SS.Formula -{ +using System; + +using NPOI.SS.Formula.PTG; - using NPOI.SS.Formula.PTG; - using System; - using System.Text; using Cysharp.Text; + +namespace NPOI.SS.Formula +{ /** * @author Josh Micich */ @@ -540,7 +541,7 @@ private Ptg AdjustPtgDueToColumnCopy(Ptg ptg) return null; } - private Ptg AdjustPtgDueToSheetMove(Ptg ptg) + private Ref3DPtg AdjustPtgDueToSheetMove(Ptg ptg) { if (ptg is Ref3DPtg refPtg) { diff --git a/main/SS/Formula/FormulaUsedBlankCellSet.cs b/main/SS/Formula/FormulaUsedBlankCellSet.cs index e74addd2a..bcd6ca4bc 100644 --- a/main/SS/Formula/FormulaUsedBlankCellSet.cs +++ b/main/SS/Formula/FormulaUsedBlankCellSet.cs @@ -15,6 +15,8 @@ the License. You may obtain a copy of the License at limitations under the License. ==================================================================== */ +using System.Collections.Generic; + namespace NPOI.SS.Formula { @@ -55,7 +57,7 @@ public class FormulaUsedBlankCellSet private class BlankCellSheetGroup { - private readonly IList _rectangleGroups; + private readonly List _rectangleGroups; private int _currentRowIndex; private int _firstColumnIndex; private int _lastColumnIndex; @@ -63,7 +65,7 @@ private class BlankCellSheetGroup public BlankCellSheetGroup() { - _rectangleGroups = new ArrayList(); + _rectangleGroups = []; _currentRowIndex = -1; } diff --git a/main/SS/Formula/Functions/AggregateFunction.cs b/main/SS/Formula/Functions/AggregateFunction.cs index 01c7a193a..aa83732d4 100644 --- a/main/SS/Formula/Functions/AggregateFunction.cs +++ b/main/SS/Formula/Functions/AggregateFunction.cs @@ -332,7 +332,7 @@ public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEva */ public abstract class AggregateFunction : MultiOperandNumericFunction { - internal static Function SubtotalInstance(Function func, bool countHiddenRows) + internal static SubtotalInstance SubtotalInstance(Function func, bool countHiddenRows) { AggregateFunction arg = (AggregateFunction)func; return new SubtotalInstance(arg, countHiddenRows); diff --git a/main/SS/Formula/Functions/Hlookup.cs b/main/SS/Formula/Functions/Hlookup.cs index 37109a18f..40f9175bf 100644 --- a/main/SS/Formula/Functions/Hlookup.cs +++ b/main/SS/Formula/Functions/Hlookup.cs @@ -16,10 +16,10 @@ the License. You may obtain a copy of the License at limitations Under the License. ==================================================================== */ +using NPOI.SS.Formula.Eval; + namespace NPOI.SS.Formula.Functions { - using NPOI.SS.Formula.Eval; - using NPOI.SS.Formula.Functions; /** * Implementation of the HLOOKUP() function.

* @@ -61,7 +61,7 @@ public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) bool IsRangeLookup = LookupUtils.ResolveRangeLookupArg(arg3, srcCellRow, srcCellCol); int colIndex = LookupUtils.lookupFirstIndexOfValue(lookupValue, LookupUtils.CreateRowVector(tableArray, 0), IsRangeLookup); int rowIndex = LookupUtils.ResolveRowOrColIndexArg(args[2], srcCellRow, srcCellCol); - ValueVector resultCol = CreateResultColumnVector(tableArray, rowIndex); + LookupUtils.RowVector resultCol = CreateResultColumnVector(tableArray, rowIndex); return resultCol.GetItem(colIndex); } catch (EvaluationException e) @@ -76,7 +76,7 @@ public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) * * @(#VALUE!) if colIndex Is negative, (#REF!) if colIndex Is too high */ - private static ValueVector CreateResultColumnVector(AreaEval tableArray, int rowIndex) + private static LookupUtils.RowVector CreateResultColumnVector(AreaEval tableArray, int rowIndex) { if (rowIndex >= tableArray.Height) { diff --git a/main/SS/Formula/Functions/LookupUtils.cs b/main/SS/Formula/Functions/LookupUtils.cs index 3a5e5a996..5690198ce 100644 --- a/main/SS/Formula/Functions/LookupUtils.cs +++ b/main/SS/Formula/Functions/LookupUtils.cs @@ -184,15 +184,16 @@ public int Size } } - - public static ValueVector CreateRowVector(TwoDEval tableArray, int relativeRowIndex) + public static RowVector CreateRowVector(TwoDEval tableArray, int relativeRowIndex) { return new RowVector((AreaEval)tableArray, relativeRowIndex); } - public static ValueVector CreateColumnVector(TwoDEval tableArray, int relativeColumnIndex) + + public static ColumnVector CreateColumnVector(TwoDEval tableArray, int relativeColumnIndex) { return new ColumnVector((AreaEval)tableArray, relativeColumnIndex); } + /** * @return null if the supplied area is neither a single row nor a single colum */ diff --git a/main/SS/Formula/Functions/Mode.cs b/main/SS/Formula/Functions/Mode.cs index fd96e47d4..74134e585 100644 --- a/main/SS/Formula/Functions/Mode.cs +++ b/main/SS/Formula/Functions/Mode.cs @@ -1,27 +1,28 @@ /* -* Licensed to the Apache Software Foundation (ASF) Under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for Additional information regarding copyright ownership. -* The ASF licenses this file to You Under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed Under the License is distributed on an "AS Is" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations Under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) Under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for Additional information regarding copyright ownership. + * The ASF licenses this file to You Under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed Under the License is distributed on an "AS Is" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations Under the License. + */ + +using System; +using System.Collections.Generic; + +using NPOI.Util; +using NPOI.SS.Formula.Eval; namespace NPOI.SS.Formula.Functions { - using System; - using System.Collections; - using NPOI.Util; - using NPOI.SS.Formula.Eval; - using NPOI.SS.Formula; /** * @author Amol S. Deshmukh < amolweb at ya hoo dot com > * @@ -76,16 +77,12 @@ public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) double result; try { - IList temp = new ArrayList(); + List temp = []; for (int i = 0; i < args.Length; i++) { CollectValues(args[i], temp); } - double[] values = new double[temp.Count]; - for (int i = 0; i < values.Length; i++) - { - values[i] = (Double)temp[i]; - } + double[] values = temp.ToArray(); result = Evaluate(values); } catch (EvaluationException e) @@ -95,7 +92,7 @@ public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) return new NumberEval(result); } - private static void CollectValues(ValueEval arg, IList temp) + private static void CollectValues(ValueEval arg, List temp) { if (arg is TwoDEval ae) { @@ -125,7 +122,7 @@ private static void CollectValues(ValueEval arg, IList temp) } - private static void CollectValue(ValueEval arg, IList temp, bool mustBeNumber) + private static void CollectValue(ValueEval arg, List temp, bool mustBeNumber) { if (arg is ErrorEval eval) { diff --git a/main/SS/Formula/Functions/Rank.cs b/main/SS/Formula/Functions/Rank.cs index 0de198d86..bfdaf7e62 100644 --- a/main/SS/Formula/Functions/Rank.cs +++ b/main/SS/Formula/Functions/Rank.cs @@ -104,7 +104,7 @@ public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEva } } - private static ValueEval eval(double arg0, AreaEval aeRange, bool descending_order) + private static NumberEval eval(double arg0, AreaEval aeRange, bool descending_order) { int rank = 1; int height = aeRange.Height; @@ -123,7 +123,8 @@ private static ValueEval eval(double arg0, AreaEval aeRange, bool descending_ord } return new NumberEval(rank); } - private static ValueEval eval(double arg0, RefListEval aeRange, bool descending_order) + + private static NumberEval eval(double arg0, RefListEval aeRange, bool descending_order) { int rank = 1; @@ -160,9 +161,9 @@ private static ValueEval eval(double arg0, RefListEval aeRange, bool descending_ return new NumberEval(rank); } + private static Double GetValue(AreaEval aeRange, int relRowIndex, int relColIndex) { - ValueEval addend = aeRange.GetRelativeValue(relRowIndex, relColIndex); if (addend is NumberEval numberEval) { @@ -184,7 +185,5 @@ private static AreaEval ConvertRangeArg(ValueEval eval) } throw new EvaluationException(ErrorEval.VALUE_INVALID); } - } - } \ No newline at end of file diff --git a/main/SS/Formula/Functions/Subtotal.cs b/main/SS/Formula/Functions/Subtotal.cs index aee3defb6..aed6b3d76 100644 --- a/main/SS/Formula/Functions/Subtotal.cs +++ b/main/SS/Formula/Functions/Subtotal.cs @@ -15,9 +15,8 @@ the License. You may obtain a copy of the License at limitations under the License. ==================================================================== */ -using System; using System.Collections.Generic; -using System.Linq; + using NPOI.SS.Formula.Eval; using NPOI.Util; @@ -111,15 +110,13 @@ public ValueEval Evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) } // ignore the first arg, this is the function-type, we check for the length above - IList list = new List(Arrays.AsList(args).GetRange(1, args.Length - 1)); - IEnumerator it = list.GetEnumerator(); + List list = new List(Arrays.AsList(args).GetRange(1, args.Length - 1)); // See https://support.office.com/en-us/article/SUBTOTAL-function-7b027003-f060-4ade-9040-e478765b9939 // "If there are other subtotals within ref1, ref2,... (or nested subtotals), these nested subtotals are ignored to avoid double counting." // For array references it is handled in1 other evaluation steps, but we need to handle this here for references to subtotal-functions - IList toRemove = new List(); - while (it.MoveNext()) + List toRemove = []; + foreach (var eval in list) { - ValueEval eval = it.Current; if (eval is LazyRefEval lazyRefEval) { if (lazyRefEval.IsSubTotal) @@ -129,8 +126,10 @@ public ValueEval Evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) } } - foreach (var x in toRemove) + foreach(var x in toRemove) + { list.Remove(x); + } return innerFunc.Evaluate(list.ToArray(), srcRowIndex, srcColumnIndex); diff --git a/main/SS/Formula/Functions/Sumproduct.cs b/main/SS/Formula/Functions/Sumproduct.cs index 41846ddd8..57ad44937 100644 --- a/main/SS/Formula/Functions/Sumproduct.cs +++ b/main/SS/Formula/Functions/Sumproduct.cs @@ -87,7 +87,7 @@ public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) + firstArg.GetType().Name + ")"); } - private static ValueEval EvaluateSingleProduct(ValueEval[] evalArgs) + private static NumberEval EvaluateSingleProduct(ValueEval[] evalArgs) { int maxN = evalArgs.Length; diff --git a/main/SS/Formula/Functions/Vlookup.cs b/main/SS/Formula/Functions/Vlookup.cs index 42b09b503..ed5e0aebf 100644 --- a/main/SS/Formula/Functions/Vlookup.cs +++ b/main/SS/Formula/Functions/Vlookup.cs @@ -102,7 +102,7 @@ public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEva bool isRangeLookup = LookupUtils.ResolveRangeLookupArg(range_lookup, srcRowIndex, srcColumnIndex); int rowIndex = LookupUtils.lookupFirstIndexOfValue(lookupValue, LookupUtils.CreateColumnVector(tableArray, 0), isRangeLookup); int colIndex = LookupUtils.ResolveRowOrColIndexArg(col_index, srcRowIndex, srcColumnIndex); - ValueVector resultCol = CreateResultColumnVector(tableArray, colIndex); + LookupUtils.ColumnVector resultCol = CreateResultColumnVector(tableArray, colIndex); return resultCol.GetItem(rowIndex); } catch (EvaluationException e) @@ -117,7 +117,7 @@ public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEva * * @(#VALUE!) if colIndex Is negative, (#REF!) if colIndex Is too high */ - private static ValueVector CreateResultColumnVector(TwoDEval tableArray, int colIndex) + private static LookupUtils.ColumnVector CreateResultColumnVector(TwoDEval tableArray, int colIndex) { if (colIndex >= tableArray.Width) { diff --git a/main/SS/Formula/WorkbookEvaluator.cs b/main/SS/Formula/WorkbookEvaluator.cs index feaf68472..03ceeece4 100644 --- a/main/SS/Formula/WorkbookEvaluator.cs +++ b/main/SS/Formula/WorkbookEvaluator.cs @@ -21,8 +21,6 @@ limitations under the License. namespace NPOI.SS.Formula { using System; - using System.Collections; - using NPOI.SS.Formula; using NPOI.SS.Formula.Eval; using NPOI.SS.Util; using NPOI.SS.Formula.Functions; @@ -57,7 +55,7 @@ public class WorkbookEvaluator private readonly Dictionary _sheetIndexesByName; private CollaboratingWorkbooksEnvironment _collaboratingWorkbookEnvironment; private readonly IStabilityClassifier _stabilityClassifier; - private readonly UDFFinder _udfFinder; + private readonly AggregatingUDFFinder _udfFinder; private bool _ignoreMissingWorkbooks = false; diff --git a/main/SS/UserModel/DataFormatter.cs b/main/SS/UserModel/DataFormatter.cs index 5b6b8bca1..8b026fbb2 100644 --- a/main/SS/UserModel/DataFormatter.cs +++ b/main/SS/UserModel/DataFormatter.cs @@ -15,23 +15,21 @@ the License. You may obtain a copy of the License at limitations under the License. ==================================================================== */ -namespace NPOI.SS.UserModel -{ - using System; - using System.Collections; - using System.Text; -using Cysharp.Text; - using System.Text.RegularExpressions; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; - using NPOI.SS.Util; - using System.Globalization; - using NPOI.SS.Format; - using NPOI.Util; - using System.Collections.Generic; - using NPOI.SS.Formula; - using System.Runtime.Serialization; +using NPOI.SS.Util; +using NPOI.SS.Format; +using NPOI.SS.Formula; +using NPOI.Util; +using Cysharp.Text; +namespace NPOI.SS.UserModel +{ /** * HSSFDataFormatter contains methods for Formatting the value stored in an * Cell. This can be useful for reports and GUI presentations when you @@ -169,7 +167,7 @@ static DataFormatter() /** * A default date format, if no date format was given */ - private readonly DateFormat defaultDateformat; + private readonly SimpleDateFormat defaultDateformat; /** General FormatBase for whole numbers. */ //private static DecimalFormat generalWholeNumFormat = new DecimalFormat("0"); @@ -186,7 +184,7 @@ static DataFormatter() * A map to cache formats. * Map Formats */ - private readonly Hashtable formats; + private readonly Dictionary formats; /** whether CSV friendly adjustments should be made to the formatted text **/ private readonly bool emulateCSV = false; @@ -267,7 +265,7 @@ public DataFormatter(CultureInfo culture, bool localeIsAdapting, bool emulateCSV defaultDateformat = new SimpleDateFormat(dateSymbols.FullDateTimePattern, dateSymbols); defaultDateformat.TimeZone = TimeZoneInfo.Local; - formats = new Hashtable(); + formats = new Dictionary(); // init built-in Formats FormatBase zipFormat = ZipPlusFourFormat.Instance; @@ -403,7 +401,8 @@ private FormatBase GetFormat(double cellValue, int formatIndex, String formatStr { formatStr = formatStr.Replace("#", ""); } - FormatBase format = (FormatBase)formats[formatStr]; + + formats.TryGetValue(formatStr, out FormatBase format); if (format != null) { return format; @@ -1170,10 +1169,8 @@ public String FormatCellValue(ICell cell, IFormulaEvaluator evaluator, Condition */ public void SetDefaultNumberFormat(FormatBase format) { - IEnumerator itr = formats.Keys.GetEnumerator(); - while (itr.MoveNext()) + foreach (var key in formats.Keys) { - string key = (string)itr.Current; if (formats[key] == generalNumberFormat) { formats[key] = format; diff --git a/main/SS/UserModel/Helpers/RowShifter.cs b/main/SS/UserModel/Helpers/RowShifter.cs index f6a46bb01..a11df033e 100644 --- a/main/SS/UserModel/Helpers/RowShifter.cs +++ b/main/SS/UserModel/Helpers/RowShifter.cs @@ -47,8 +47,8 @@ public RowShifter(ISheet sh) /// an array of affected merged regions, doesn't contain deleted ones public List ShiftMergedRegions(int startRow, int endRow, int n) { - var ShiftedRegions = new List(); - ISet removedIndices = new HashSet(); + List ShiftedRegions = []; + HashSet removedIndices = []; var size = sheet.NumMergedRegions; for (var i = 0; i < size; i++) diff --git a/main/SS/Util/CellUtil.cs b/main/SS/Util/CellUtil.cs index 881489745..bde441844 100644 --- a/main/SS/Util/CellUtil.cs +++ b/main/SS/Util/CellUtil.cs @@ -58,42 +58,36 @@ public class CellUtil public const string VERTICAL_ALIGNMENT = "verticalAlignment"; public const string WRAP_TEXT = "wrapText"; - private static ISet shortValues = new HashSet(new string[]{ - BOTTOM_BORDER_COLOR, - LEFT_BORDER_COLOR, - RIGHT_BORDER_COLOR, - TOP_BORDER_COLOR, - FILL_FOREGROUND_COLOR, - FILL_BACKGROUND_COLOR, - INDENTION, - DATA_FORMAT, - ROTATION - }); - private static ISet intValues = new HashSet(new string[]{ - FONT - }); - private static ISet booleanValues = new HashSet(new string[]{ - LOCKED, - HIDDEN, - WRAP_TEXT - }); - private static ISet borderTypeValues = new HashSet(new string[]{ - BORDER_BOTTOM, - BORDER_LEFT, - BORDER_RIGHT, - BORDER_TOP - }); - - - private static UnicodeMapping[] unicodeMappings; + private static readonly HashSet shortValues = + [ + BOTTOM_BORDER_COLOR, + LEFT_BORDER_COLOR, + RIGHT_BORDER_COLOR, + TOP_BORDER_COLOR, + FILL_FOREGROUND_COLOR, + FILL_BACKGROUND_COLOR, + INDENTION, + DATA_FORMAT, + ROTATION + ]; + + private static readonly HashSet intValues = [FONT]; + + private static readonly HashSet booleanValues = [LOCKED, HIDDEN, WRAP_TEXT]; + + private static readonly HashSet borderTypeValues = + [ + BORDER_BOTTOM, BORDER_LEFT, BORDER_RIGHT, BORDER_TOP + ]; + + private static readonly UnicodeMapping[] unicodeMappings; private sealed class UnicodeMapping { + public readonly string entityName; + public readonly string resolvedValue; - public String entityName; - public String resolvedValue; - - public UnicodeMapping(String pEntityName, String pResolvedValue) + public UnicodeMapping(string pEntityName, string pResolvedValue) { entityName = "&" + pEntityName + ";"; resolvedValue = pResolvedValue; diff --git a/main/Util/RLEDecompressingInputStream.cs b/main/Util/RLEDecompressingInputStream.cs index 901cd2d50..5cb354eee 100644 --- a/main/Util/RLEDecompressingInputStream.cs +++ b/main/Util/RLEDecompressingInputStream.cs @@ -323,7 +323,7 @@ private static int ReadShort(Stream stream) return (b0 & 0xFF) | ((b1 & 0xFF) << 8); } - private static int ReadInt(InputStream stream) + private static int ReadInt(RLEDecompressingInputStream stream) { int b0, b1, b2, b3; if ((b0 = stream.Read()) == -1) @@ -352,9 +352,9 @@ public static byte[] Decompress(byte[] compressed) public static byte[] Decompress(byte[] compressed, int offset, int length) { - MemoryStream out1 = new MemoryStream(); - Stream instream = new MemoryStream(compressed, offset, length); - InputStream stream = new RLEDecompressingInputStream(instream); + using MemoryStream out1 = new MemoryStream(); + using Stream instream = new MemoryStream(compressed, offset, length); + using RLEDecompressingInputStream stream = new RLEDecompressingInputStream(instream); IOUtils.Copy(stream, out1); stream.Close(); out1.Close(); diff --git a/ooxml/POIFS/Crypt/Agile/AgileEncryptionVerifier.cs b/ooxml/POIFS/Crypt/Agile/AgileEncryptionVerifier.cs index 77c23c1de..98dd46e6c 100644 --- a/ooxml/POIFS/Crypt/Agile/AgileEncryptionVerifier.cs +++ b/ooxml/POIFS/Crypt/Agile/AgileEncryptionVerifier.cs @@ -47,7 +47,7 @@ public AgileEncryptionVerifier(String descriptor) protected internal AgileEncryptionVerifier(EncryptionDocument ed) { - IEnumerator encList = ed.GetEncryption().keyEncryptors.keyEncryptor.GetEnumerator(); + List.Enumerator encList = ed.GetEncryption().keyEncryptors.keyEncryptor.GetEnumerator(); CT_PasswordKeyEncryptor keyData; try { diff --git a/ooxml/XSSF/Extractor/XSSFExportToXml.cs b/ooxml/XSSF/Extractor/XSSFExportToXml.cs index a8a9853d3..dbf4aa419 100644 --- a/ooxml/XSSF/Extractor/XSSFExportToXml.cs +++ b/ooxml/XSSF/Extractor/XSSFExportToXml.cs @@ -335,7 +335,7 @@ private static String RemoveNamespace(String elementName) private static String GetFormattedDate(XSSFCell cell) { - DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.TimeZone= LocaleUtil.GetUserTimeZoneInfo(); return sdf.Format(cell.DateCellValue); } diff --git a/ooxml/XSSF/Streaming/SXSSFCell.cs b/ooxml/XSSF/Streaming/SXSSFCell.cs index ec2bbcbe6..3f0d4ff2c 100644 --- a/ooxml/XSSF/Streaming/SXSSFCell.cs +++ b/ooxml/XSSF/Streaming/SXSSFCell.cs @@ -595,7 +595,7 @@ public override string ToString() case CellType.Numeric: if (DateUtil.IsCellDateFormatted(this)) { - FormatBase sdf = new SimpleDateFormat("dd-MMM-yyyy"); + SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); //sdf.setTimeZone(LocaleUtil.getUserTimeZone()); return sdf.Format(DateCellValue); } diff --git a/ooxml/XSSF/Streaming/SheetDataWriter.cs b/ooxml/XSSF/Streaming/SheetDataWriter.cs index f9c9e355b..55fe94f0a 100644 --- a/ooxml/XSSF/Streaming/SheetDataWriter.cs +++ b/ooxml/XSSF/Streaming/SheetDataWriter.cs @@ -136,7 +136,7 @@ public FileInfo TempFileInfo */ public Stream GetWorksheetXmlInputStream() { - Stream fis = new FileStream(TemporaryFileInfo.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite); + FileStream fis = new FileStream(TemporaryFileInfo.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite); try { return DecorateInputStream(fis); diff --git a/ooxml/XSSF/UserModel/Helpers/ColumnShifter.cs b/ooxml/XSSF/UserModel/Helpers/ColumnShifter.cs index a58bac4d7..5026dae5f 100644 --- a/ooxml/XSSF/UserModel/Helpers/ColumnShifter.cs +++ b/ooxml/XSSF/UserModel/Helpers/ColumnShifter.cs @@ -15,12 +15,12 @@ the License. You may obtain a copy of the License at limitations under the License. ==================================================================== */ +using System.Collections.Generic; +using System.Linq; + using NPOI.SS.Formula; using NPOI.SS.UserModel; using NPOI.SS.Util; -using System; -using System.Collections.Generic; -using System.Linq; namespace NPOI.XSSF.UserModel.Helpers { @@ -53,8 +53,8 @@ public List ShiftMergedRegions( int endColumn, int n) { - List shiftedRegions = new List(); - ISet removedIndices = new HashSet(); + List shiftedRegions = []; + HashSet removedIndices = []; //move merged regions completely if they fall within the new region //boundaries when they are Shifted int size = sheet.NumMergedRegions; diff --git a/ooxml/XSSF/UserModel/Helpers/XSSFIgnoredErrorHelper.cs b/ooxml/XSSF/UserModel/Helpers/XSSFIgnoredErrorHelper.cs index 89fbf79dd..edab89263 100644 --- a/ooxml/XSSF/UserModel/Helpers/XSSFIgnoredErrorHelper.cs +++ b/ooxml/XSSF/UserModel/Helpers/XSSFIgnoredErrorHelper.cs @@ -103,10 +103,10 @@ public static void AddIgnoredErrors(CT_IgnoredError err, String ref1, params Ign public static ISet GetErrorTypes(CT_IgnoredError err) { - ISet result = new HashSet(); + HashSet result = []; foreach (IgnoredErrorType errType in IgnoredErrorTypeValues.Values) { - if (XSSFIgnoredErrorHelper.IsSet(errType, err)) + if (IsSet(errType, err)) { result.Add(errType); } diff --git a/ooxml/XSSF/UserModel/XSSFCell.cs b/ooxml/XSSF/UserModel/XSSFCell.cs index ae8b5f8bd..42b49450a 100644 --- a/ooxml/XSSF/UserModel/XSSFCell.cs +++ b/ooxml/XSSF/UserModel/XSSFCell.cs @@ -660,7 +660,8 @@ internal void TryToDeleteArrayFormula(String message) //un-register the single-cell array formula from the parent sheet through public interface Row.Sheet.RemoveArrayFormula(this); } - private ICell SetFormula(String formula, FormulaType formulaType) + + private XSSFCell SetFormula(String formula, FormulaType formulaType) { XSSFWorkbook wb = (XSSFWorkbook)_row.Sheet.Workbook; if (formula == null) @@ -1090,7 +1091,7 @@ public override String ToString() case CellType.Numeric: if (DateUtil.IsCellDateFormatted(this)) { - FormatBase sdf = new SimpleDateFormat("dd-MMM-yyyy"); + SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); return sdf.Format(DateCellValue, CultureInfo.CurrentCulture); } return NumericCellValue.ToString(); @@ -1140,7 +1141,7 @@ private static String GetCellTypeName(CellType cellTypeCode) /** * Used to help format error messages */ - private static Exception TypeMismatch(CellType expectedTypeCode, CellType actualTypeCode, bool isFormulaCell) + private static InvalidOperationException TypeMismatch(CellType expectedTypeCode, CellType actualTypeCode, bool isFormulaCell) { String msg = "Cannot get a " + GetCellTypeName(expectedTypeCode) + " value from a " diff --git a/ooxml/XSSF/UserModel/XSSFSheet.cs b/ooxml/XSSF/UserModel/XSSFSheet.cs index 85ecd3255..960970fbc 100644 --- a/ooxml/XSSF/UserModel/XSSFSheet.cs +++ b/ooxml/XSSF/UserModel/XSSFSheet.cs @@ -1591,7 +1591,7 @@ CT_Hyperlink[] ctHls } } - internal bool IsCellInArrayFormulaContext(ICell cell) + internal bool IsCellInArrayFormulaContext(XSSFCell cell) { foreach(CellRangeAddress range in arrayFormulas) { @@ -1604,7 +1604,7 @@ internal bool IsCellInArrayFormulaContext(ICell cell) return false; } - internal XSSFCell GetFirstCellInArrayFormula(ICell cell) + internal XSSFCell GetFirstCellInArrayFormula(XSSFCell cell) { foreach(CellRangeAddress range in arrayFormulas) { @@ -2996,8 +2996,8 @@ public void CopyRows(List srcRows, int destStartRow, CellCopyPolicy pol throw new ArgumentException("No rows to copy"); } - IRow srcStartRow = srcRows[0]; - IRow srcEndRow = srcRows[srcRows.Count - 1]; + XSSFRow srcStartRow = srcRows[0]; + XSSFRow srcEndRow = srcRows[srcRows.Count - 1]; if(srcStartRow == null) { @@ -3012,7 +3012,7 @@ public void CopyRows(List srcRows, int destStartRow, CellCopyPolicy pol int size = srcRows.Count; for(int index = 1; index < size; index++) { - IRow curRow = srcRows[index]; + XSSFRow curRow = srcRows[index]; if(curRow == null) { throw new ArgumentException( @@ -3565,8 +3565,7 @@ public void LockSelectUnlockedCells(bool enabled) public ICellRange SetArrayFormula(string formula, CellRangeAddress range) { - - ICellRange cr = GetCellRange(range); + SSCellRange cr = GetCellRange(range); ICell mainArrayFormulaCell = cr.TopLeftCell; ((XSSFCell) mainArrayFormulaCell).SetCellArrayFormula(formula, range); @@ -4181,7 +4180,7 @@ public void CopyTo(IWorkbook dest, string name, bool copyStyle, bool keepFormula XSSFSheet newSheet = (XSSFSheet) dest.CreateSheet(name); newSheet.sheet.state = sheet.state; - IDictionary styleMap = copyStyle ? new Dictionary() : null; + Dictionary styleMap = copyStyle ? new Dictionary() : null; for(int i = FirstRowNum; i <= LastRowNum; i++) { XSSFRow srcRow = (XSSFRow) GetRow(i); @@ -5669,7 +5668,7 @@ private bool IsSheetProtectionEnabled() ///

/// /// - private ICellRange GetCellRange(CellRangeAddress range) + private SSCellRange GetCellRange(CellRangeAddress range) { int firstRow = range.FirstRow; int firstColumn = range.FirstColumn; @@ -5955,7 +5954,7 @@ private static XSSFPictureData FindPicture(IList sheetPictur } private static void CopyRow(XSSFSheet srcSheet, XSSFSheet destSheet, XSSFRow srcRow, XSSFRow destRow, - IDictionary styleMap, bool keepFormulas, bool keepMergedRegion) + Dictionary styleMap, bool keepFormulas, bool keepMergedRegion) { destRow.Height = srcRow.Height; if(!srcRow.GetCTRow().IsSetCustomHeight()) @@ -6017,8 +6016,7 @@ private static void CopyRow(XSSFSheet srcSheet, XSSFSheet destSheet, XSSFRow src } } - private static void CopyCell(ICell oldCell, ICell newCell, IDictionary styleMap, - bool keepFormulas) + private static void CopyCell(XSSFCell oldCell, XSSFCell newCell, Dictionary styleMap, bool keepFormulas) { if(styleMap != null) { @@ -6206,9 +6204,9 @@ private void AddIgnoredErrors(string ref1, params IgnoredErrorType[] ignoredErro XSSFIgnoredErrorHelper.AddIgnoredErrors(ctIgnoredError, ref1, ignoredErrorTypes); } - private static ISet GetErrorTypes(CT_IgnoredError err) + private static HashSet GetErrorTypes(CT_IgnoredError err) { - ISet result = new HashSet(); + HashSet result = []; foreach(IgnoredErrorType errType in IgnoredErrorTypeValues.Values) { diff --git a/ooxml/XSSF/UserModel/XSSFWorkbook.cs b/ooxml/XSSF/UserModel/XSSFWorkbook.cs index a02e24307..3c7f06a0b 100644 --- a/ooxml/XSSF/UserModel/XSSFWorkbook.cs +++ b/ooxml/XSSF/UserModel/XSSFWorkbook.cs @@ -2311,7 +2311,7 @@ private void CreateProtectionFieldIfNotPresent() * @return wrapped instance of UDFFinder that allows seeking functions both by index and name */ /*package*/ - internal UDFFinder GetUDFFinder() + internal IndexedUDFFinder GetUDFFinder() { return _udfFinder; } diff --git a/ooxml/XWPF/Usermodel/XWPFDocument.cs b/ooxml/XWPF/Usermodel/XWPFDocument.cs index 07f899064..75a7e0e2a 100644 --- a/ooxml/XWPF/Usermodel/XWPFDocument.cs +++ b/ooxml/XWPF/Usermodel/XWPFDocument.cs @@ -19,18 +19,17 @@ limitations under the License. namespace NPOI.XWPF.UserModel { using System; + using System.Collections.Generic; using System.IO; + using System.Linq; + using System.Xml; + using NPOI.Util; - using System.Collections.Generic; using NPOI.OpenXml4Net.OPC; using NPOI.OpenXmlFormats.Wordprocessing; - using System.Xml; using NPOI.WP.UserModel; using NPOI.XWPF.Model; - using System.Xml.Serialization; - using System.Diagnostics; using NPOI.OOXML.XWPF.Util; - using System.Linq; using NPOI.POIFS.Crypt; /** @@ -449,10 +448,8 @@ public String GetTblStyle(XWPFTable table) public XWPFHyperlink GetHyperlinkByID(String id) { - IEnumerator iter = hyperlinks.GetEnumerator(); - while (iter.MoveNext()) + foreach (XWPFHyperlink link in hyperlinks) { - XWPFHyperlink link = iter.Current; if (link.Id.Equals(id)) return link; } @@ -462,16 +459,11 @@ public XWPFHyperlink GetHyperlinkByID(String id) public XWPFFootnote GetFootnoteByID(int id) { - if (footnotes == null) return null; - return footnotes.GetFootnoteById(id); - } - public Dictionary Endnotes - { - get - { - return endnotes; - } + return footnotes?.GetFootnoteById(id); } + + public Dictionary Endnotes => endnotes; + public XWPFFootnote GetEndnoteByID(int id) { if (endnotes == null || !endnotes.TryGetValue(id, out XWPFFootnote byId)) @@ -483,7 +475,7 @@ public List GetFootnotes() { if (footnotes == null) { - return new List(); + return []; } return footnotes.GetFootnotesList(); } @@ -1589,18 +1581,15 @@ public XWPFPictureData FindPackagePictureData(byte[] pictureData, int format) * Try to find PictureData with this Checksum. Create new, if none * exists. */ - List xwpfPicDataList = null; - if(packagePictures.TryGetValue(Checksum, out List picture)) - xwpfPicDataList = picture; - if (xwpfPicDataList != null) + + if (packagePictures.TryGetValue(Checksum, out List xwpfPicDataList)) { - IEnumerator iter = xwpfPicDataList.GetEnumerator(); - while (iter.MoveNext() && xwpfPicData == null) + foreach (XWPFPictureData curElem in xwpfPicDataList) { - XWPFPictureData curElem = iter.Current; if (Arrays.Equals(pictureData, curElem.Data)) { xwpfPicData = curElem; + break; } } } diff --git a/ooxml/XWPF/Usermodel/XWPFFooter.cs b/ooxml/XWPF/Usermodel/XWPFFooter.cs index c5b077c5d..1ed3d2511 100644 --- a/ooxml/XWPF/Usermodel/XWPFFooter.cs +++ b/ooxml/XWPF/Usermodel/XWPFFooter.cs @@ -175,10 +175,8 @@ public List GetHyperlinks() public XWPFHyperlink GetHyperlinkByID(string id) { - IEnumerator iter = hyperlinks.GetEnumerator(); - while (iter.MoveNext()) + foreach (XWPFHyperlink link in hyperlinks) { - XWPFHyperlink link = iter.Current; if (link.Id.Equals(id)) return link; } diff --git a/ooxml/XWPF/Usermodel/XWPFFootnotes.cs b/ooxml/XWPF/Usermodel/XWPFFootnotes.cs index e6dff9bb9..74c4d67e2 100644 --- a/ooxml/XWPF/Usermodel/XWPFFootnotes.cs +++ b/ooxml/XWPF/Usermodel/XWPFFootnotes.cs @@ -15,17 +15,16 @@ the License. You may obtain a copy of the License at limitations under the License. ==================================================================== */ -namespace NPOI.XWPF.UserModel -{ - using System; - using System.Collections.Generic; - using NPOI.OpenXmlFormats.Wordprocessing; - using NPOI.OpenXml4Net.OPC; - using System.IO; - using System.Xml; - using System.Xml.Serialization; +using System; +using System.Collections.Generic; +using System.IO; +using System.Xml; +using NPOI.OpenXmlFormats.Wordprocessing; +using NPOI.OpenXml4Net.OPC; +namespace NPOI.XWPF.UserModel +{ /** * Looks After the collection of Footnotes for a document * @@ -33,9 +32,9 @@ namespace NPOI.XWPF.UserModel */ public class XWPFFootnotes : POIXMLDocumentPart { - private List listFootnote = new List(); + private readonly List listFootnote = []; private CT_Footnotes ctFootnotes; - private List hyperlinks = new List(); + private readonly List hyperlinks = []; protected XWPFDocument document; @@ -244,14 +243,14 @@ public XWPFDocument GetXWPFDocument() } } - public XWPFHyperlink GetHyperlinkByID(String id) + public XWPFHyperlink GetHyperlinkByID(string id) { - IEnumerator iter = hyperlinks.GetEnumerator(); - while (iter.MoveNext()) + foreach (XWPFHyperlink link in hyperlinks) { - XWPFHyperlink link = iter.Current; - if (link.Id.Equals(id)) + if(link.Id.Equals(id)) + { return link; + } } return null; diff --git a/openxml4Net/OPC/Internal/Unmarshallers/PackagePropertiesUnmarshaller.cs b/openxml4Net/OPC/Internal/Unmarshallers/PackagePropertiesUnmarshaller.cs index 9d24d2f22..83931ceb0 100644 --- a/openxml4Net/OPC/Internal/Unmarshallers/PackagePropertiesUnmarshaller.cs +++ b/openxml4Net/OPC/Internal/Unmarshallers/PackagePropertiesUnmarshaller.cs @@ -1,12 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Xml; +using System.Collections; using System.IO; -using System.Collections; +using System.Xml; + using NPOI.OpenXml4Net.Exceptions; -using ICSharpCode.SharpZipLib.Zip; using NPOI.Util; + +using ICSharpCode.SharpZipLib.Zip; + namespace NPOI.OpenXml4Net.OPC.Internal.Unmarshallers { /** @@ -17,52 +17,51 @@ namespace NPOI.OpenXml4Net.OPC.Internal.Unmarshallers */ public class PackagePropertiesUnmarshaller : PartUnmarshaller { + private const string namespaceDC = "http://purl.org/dc/elements/1.1/"; + private const string namespaceCP = PackageNamespaces.CORE_PROPERTIES; + private const string namespaceDcTerms = "http://purl.org/dc/terms/"; - private static string namespaceDC = "http://purl.org/dc/elements/1.1/"; - - private static string namespaceCP = PackageNamespaces.CORE_PROPERTIES; - private static string namespaceDcTerms = "http://purl.org/dc/terms/"; + private const string namespaceXML = "http://www.w3.org/XML/1998/namespace"; - private static string namespaceXML = "http://www.w3.org/XML/1998/namespace"; + private const string namespaceXSI = "http://www.w3.org/2001/XMLSchema-instance"; - private static string namespaceXSI = "http://www.w3.org/2001/XMLSchema-instance"; + protected static string KEYWORD_CATEGORY = "category"; - protected static String KEYWORD_CATEGORY = "category"; + protected static string KEYWORD_CONTENT_STATUS = "contentStatus"; - protected static String KEYWORD_CONTENT_STATUS = "contentStatus"; + protected static string KEYWORD_CONTENT_TYPE = "contentType"; - protected static String KEYWORD_CONTENT_TYPE = "contentType"; + protected static string KEYWORD_CREATED = "created"; - protected static String KEYWORD_CREATED = "created"; + protected static string KEYWORD_CREATOR = "creator"; - protected static String KEYWORD_CREATOR = "creator"; + protected static string KEYWORD_DESCRIPTION = "description"; - protected static String KEYWORD_DESCRIPTION = "description"; + protected static string KEYWORD_IDENTIFIER = "identifier"; - protected static String KEYWORD_IDENTIFIER = "identifier"; + protected static string KEYWORD_KEYWORDS = "keywords"; - protected static String KEYWORD_KEYWORDS = "keywords"; + protected static string KEYWORD_LANGUAGE = "language"; - protected static String KEYWORD_LANGUAGE = "language"; + protected static string KEYWORD_LAST_MODIFIED_BY = "lastModifiedBy"; - protected static String KEYWORD_LAST_MODIFIED_BY = "lastModifiedBy"; + protected static string KEYWORD_LAST_PRINTED = "lastPrinted"; - protected static String KEYWORD_LAST_PRINTED = "lastPrinted"; + protected static string KEYWORD_MODIFIED = "modified"; - protected static String KEYWORD_MODIFIED = "modified"; + protected static string KEYWORD_REVISION = "revision"; - protected static String KEYWORD_REVISION = "revision"; + protected static string KEYWORD_SUBJECT = "subject"; - protected static String KEYWORD_SUBJECT = "subject"; + protected static string KEYWORD_TITLE = "title"; - protected static String KEYWORD_TITLE = "title"; + protected static string KEYWORD_VERSION = "version"; - protected static String KEYWORD_VERSION = "version"; + protected XmlNamespaceManager nsmgr; - protected XmlNamespaceManager nsmgr = null; // TODO Load element with XMLBeans or dynamic table // TODO Check every element/namespace for compliance public PackagePart Unmarshall(UnmarshallContext context, Stream in1) @@ -158,7 +157,7 @@ public PackagePart Unmarshall(UnmarshallContext context, Stream in1) return coreProps; } - private String LoadCategory(XmlDocument xmlDoc) + private string LoadCategory(XmlDocument xmlDoc) { XmlNode el = xmlDoc.DocumentElement.SelectNodes("cp:" + KEYWORD_CATEGORY, nsmgr)[0]; @@ -169,7 +168,7 @@ private String LoadCategory(XmlDocument xmlDoc) return el.InnerText; } - private String LoadContentStatus(XmlDocument xmlDoc) + private string LoadContentStatus(XmlDocument xmlDoc) { XmlNode el = xmlDoc.DocumentElement.SelectNodes("cp:" + KEYWORD_CONTENT_STATUS, nsmgr)[0]; if (el == null) @@ -179,7 +178,7 @@ private String LoadContentStatus(XmlDocument xmlDoc) return el.InnerText; } - private String LoadContentType(XmlDocument xmlDoc) + private string LoadContentType(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_CONTENT_TYPE, namespaceCP)); @@ -191,7 +190,7 @@ private String LoadContentType(XmlDocument xmlDoc) return el.InnerText; } - private String LoadCreated(XmlDocument xmlDoc) + private string LoadCreated(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_CREATED, namespaceDcTerms)); @@ -203,7 +202,7 @@ private String LoadCreated(XmlDocument xmlDoc) return el.InnerText; } - private String LoadCreator(XmlDocument xmlDoc) + private string LoadCreator(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_CREATOR, namespaceDC)); @@ -215,7 +214,7 @@ private String LoadCreator(XmlDocument xmlDoc) return el.InnerText; } - private String LoadDescription(XmlDocument xmlDoc) + private string LoadDescription(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_DESCRIPTION, namespaceDC)); @@ -227,7 +226,7 @@ private String LoadDescription(XmlDocument xmlDoc) return el.InnerText; } - private String LoadIdentifier(XmlDocument xmlDoc) + private string LoadIdentifier(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_IDENTIFIER, namespaceDC)); @@ -239,7 +238,7 @@ private String LoadIdentifier(XmlDocument xmlDoc) return el.InnerText; } - private String LoadKeywords(XmlDocument xmlDoc) + private string LoadKeywords(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_KEYWORDS, namespaceCP)); @@ -252,7 +251,7 @@ private String LoadKeywords(XmlDocument xmlDoc) return el.InnerText; } - private String LoadLanguage(XmlDocument xmlDoc) + private string LoadLanguage(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_LANGUAGE, namespaceDC)); @@ -264,7 +263,7 @@ private String LoadLanguage(XmlDocument xmlDoc) return el.InnerText; } - private String LoadLastModifiedBy(XmlDocument xmlDoc) + private string LoadLastModifiedBy(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_LAST_MODIFIED_BY, namespaceCP)); @@ -276,7 +275,7 @@ private String LoadLastModifiedBy(XmlDocument xmlDoc) return el.InnerText; } - private String LoadLastPrinted(XmlDocument xmlDoc) + private string LoadLastPrinted(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_LAST_PRINTED, namespaceCP)); @@ -288,7 +287,7 @@ private String LoadLastPrinted(XmlDocument xmlDoc) return el.InnerText; } - private String LoadModified(XmlDocument xmlDoc) + private string LoadModified(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_MODIFIED, namespaceDcTerms)); @@ -300,7 +299,7 @@ private String LoadModified(XmlDocument xmlDoc) return el.InnerText; } - private String LoadRevision(XmlDocument xmlDoc) + private string LoadRevision(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_REVISION, namespaceCP)); @@ -312,7 +311,7 @@ private String LoadRevision(XmlDocument xmlDoc) return el.InnerText; } - private String LoadSubject(XmlDocument xmlDoc) + private string LoadSubject(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_SUBJECT, namespaceDC)); @@ -324,7 +323,7 @@ private String LoadSubject(XmlDocument xmlDoc) return el.InnerText; } - private String LoadTitle(XmlDocument xmlDoc) + private string LoadTitle(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_TITLE, namespaceDC)); @@ -336,7 +335,7 @@ private String LoadTitle(XmlDocument xmlDoc) return el.InnerText; } - private String LoadVersion(XmlDocument xmlDoc) + private string LoadVersion(XmlDocument xmlDoc) { //Element el = xmlDoc.getRootElement().element( // new QName(KEYWORD_VERSION, namespaceCP)); @@ -415,7 +414,7 @@ public void CheckElementForOPCCompliance(XmlElement el) + PackageNamespaces.NAMESPACE_DCTERMS); // Check for the 'xsi:type' attribute - XmlNode typeAtt = el.Attributes["type", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI];// el.Attributes["xsi:type"]; + XmlAttribute typeAtt = el.Attributes["type", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI];// el.Attributes["xsi:type"]; if (typeAtt == null) throw new InvalidFormatException("The element '" + elName + "' must have the '" + nsmgr.LookupPrefix(namespaceXSI) diff --git a/openxml4Net/OPC/Internal/ZipContentTypeManager.cs b/openxml4Net/OPC/Internal/ZipContentTypeManager.cs index ad0d45b42..52162725c 100644 --- a/openxml4Net/OPC/Internal/ZipContentTypeManager.cs +++ b/openxml4Net/OPC/Internal/ZipContentTypeManager.cs @@ -1,71 +1,78 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.IO; +using System.IO; using System.Xml; using ICSharpCode.SharpZipLib.Zip; using NPOI.Util; + namespace NPOI.OpenXml4Net.OPC.Internal { -/** - * Zip implementation of the ContentTypeManager. - * - * @author Julien Chable - * @version 1.0 - * @see ContentTypeManager - */ -public class ZipContentTypeManager:ContentTypeManager { - - private static POILogger logger = POILogFactory.GetLogger(typeof(ZipContentTypeManager)); - /** - * Delegate constructor to the super constructor. - * - * @param in - * The input stream to parse to fill internal content type - * collections. - * @throws InvalidFormatException - * If the content types part content is not valid. - */ - public ZipContentTypeManager(Stream in1, OPCPackage pkg):base(in1, pkg) - { - - } + /** + * Zip implementation of the ContentTypeManager. + * + * @author Julien Chable + * @version 1.0 + * @see ContentTypeManager + */ + public class ZipContentTypeManager : ContentTypeManager + { + private static readonly POILogger logger = POILogFactory.GetLogger(typeof(ZipContentTypeManager)); + + /** + * Delegate constructor to the super constructor. + * + * @param in + * The input stream to parse to fill internal content type + * collections. + * @throws InvalidFormatException + * If the content types part content is not valid. + */ + public ZipContentTypeManager(Stream in1, OPCPackage pkg) : base(in1, pkg) + { + } + + + public override bool SaveImpl(XmlDocument content, Stream out1) + { + ZipOutputStream zos = null; + if(out1 is ZipOutputStream stream) + zos = stream; + else + zos = new ZipOutputStream(out1); - - public override bool SaveImpl(XmlDocument content, Stream out1) { - ZipOutputStream zos = null; - if (out1 is ZipOutputStream stream) - zos = stream; - else - zos = new ZipOutputStream(out1); + ZipEntry partEntry = new ZipEntry(CONTENT_TYPES_PART_NAME); + try + { + // Referenced in ZIP + zos.PutNextEntry(partEntry); + // Saving data in the ZIP file - ZipEntry partEntry = new ZipEntry(CONTENT_TYPES_PART_NAME); - try { - // Referenced in ZIP - zos.PutNextEntry(partEntry); - // Saving data in the ZIP file - - StreamHelper.SaveXmlInStream(content, out1); - Stream ins = new MemoryStream(); - - byte[] buff = new byte[ZipHelper.READ_WRITE_FILE_BUFFER_SIZE]; - while (true) { - int resultRead = ins.Read(buff, 0, ZipHelper.READ_WRITE_FILE_BUFFER_SIZE); - if (resultRead == 0) { - // end of file reached - break; - } else { - zos.Write(buff, 0, resultRead); + StreamHelper.SaveXmlInStream(content, out1); + using MemoryStream ins = new MemoryStream(); + + byte[] buff = new byte[ZipHelper.READ_WRITE_FILE_BUFFER_SIZE]; + while(true) + { + int resultRead = ins.Read(buff, 0, ZipHelper.READ_WRITE_FILE_BUFFER_SIZE); + if(resultRead == 0) + { + // end of file reached + break; + } + else + { + zos.Write(buff, 0, resultRead); + } } + + zos.CloseEntry(); + } + catch(IOException ioe) + { + logger.Log(POILogger.ERROR, "Cannot write: " + CONTENT_TYPES_PART_NAME + + " in Zip !", ioe); + return false; } - zos.CloseEntry(); - } catch (IOException ioe) { - logger.Log(POILogger.ERROR, "Cannot write: " + CONTENT_TYPES_PART_NAME - + " in Zip !", ioe); - return false; - } - return true; - } -} -} + return true; + } + } +} \ No newline at end of file