Skip to content

Commit 6eefe8c

Browse files
Minor refactoring (#849)
Taken care of a some warnings, removed unused imports, added pattern matching where deemed appropriate, general code and comment cleanup
1 parent 74ff1af commit 6eefe8c

37 files changed

+672
-765
lines changed

src/MiniExcel.Core/Abstractions/IMiniExcelWriteAdapter.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using MiniExcelLib.Core.Reflection;
2-
3-
namespace MiniExcelLib.Core.Abstractions;
1+
namespace MiniExcelLib.Core.Abstractions;
42

53
public interface IMiniExcelWriteAdapter
64
{

src/MiniExcel.Core/Abstractions/IMiniExcelWriteAdapterAsync.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using MiniExcelLib.Core.Reflection;
2-
3-
namespace MiniExcelLib.Core.Abstractions;
1+
namespace MiniExcelLib.Core.Abstractions;
42

53
public interface IMiniExcelWriteAdapterAsync
64
{

src/MiniExcel.Core/DataReader/MiniExcelDataReaderBase.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using MiniExcelLib.Core.Abstractions;
2-
3-
namespace MiniExcelLib.Core.DataReader;
1+
namespace MiniExcelLib.Core.DataReader;
42

53
/// <summary>
64
/// IMiniExcelDataReader Base Class

src/MiniExcel.Core/OpenXml/Constants/ExcelXml.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
using MiniExcelLib.Core.Helpers;
2-
using MiniExcelLib.Core.OpenXml.Models;
1+
using MiniExcelLib.Core.OpenXml.Models;
32

43
namespace MiniExcelLib.Core.OpenXml.Constants;
54

src/MiniExcel.Core/OpenXml/Models/ExcelWidthCollection.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
using MiniExcelLib.Core.Reflection;
2-
31
namespace MiniExcelLib.Core.OpenXml.Models;
42

53
public sealed class ExcelColumnWidth

src/MiniExcel.Core/OpenXml/OpenXmlReader.cs

Lines changed: 18 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,14 @@
11
using System.Collections.ObjectModel;
2-
using MiniExcelLib.Core.Helpers;
32
using MiniExcelLib.Core.OpenXml.Constants;
43
using MiniExcelLib.Core.OpenXml.Models;
54
using MiniExcelLib.Core.OpenXml.Styles;
6-
using MiniExcelLib.Core.OpenXml.Utils;
75
using MiniExcelLib.Core.OpenXml.Zip;
8-
using MiniExcelLib.Core.Reflection;
96
using MiniExcelMapper = MiniExcelLib.Core.Reflection.MiniExcelMapper;
107
using XmlReaderHelper = MiniExcelLib.Core.OpenXml.Utils.XmlReaderHelper;
118

129
namespace MiniExcelLib.Core.OpenXml;
1310

14-
internal partial class OpenXmlReader : Abstractions.IMiniExcelReader
11+
internal partial class OpenXmlReader : IMiniExcelReader
1512
{
1613
private static readonly string[] Ns = [Schemas.SpreadsheetmlXmlns, Schemas.SpreadsheetmlXmlStrictns];
1714
private static readonly string[] RelationshiopNs = [Schemas.SpreadsheetmlXmlRelationshipns, Schemas.SpreadsheetmlXmlStrictRelationshipns];
@@ -22,7 +19,7 @@ internal partial class OpenXmlReader : Abstractions.IMiniExcelReader
2219
private bool _disposed;
2320

2421
internal readonly OpenXmlZip Archive;
25-
internal IDictionary<int, string>? SharedStrings;
22+
internal IDictionary<int, string> SharedStrings = new Dictionary<int, string>();
2623

2724
private OpenXmlReader(Stream stream, IMiniExcelConfiguration? configuration)
2825
{
@@ -217,10 +214,8 @@ await XmlReaderHelper.SkipToNextSameLevelDomAsync(reader, cancellationToken)
217214

218215
await foreach (var row in QueryRowAsync(reader, isFirstRow, startRowIndex, nextRowIndex,
219216
rowIndex, startColumnIndex, endColumnIndex, maxColumnIndex,
220-
withoutCr,
221-
useHeaderRow, headRows, mergeCellsContext.MergeCells,
222-
cancellationToken)
223-
.ConfigureAwait(false))
217+
withoutCr, useHeaderRow, headRows, mergeCellsContext.MergeCells,
218+
cancellationToken).ConfigureAwait(false))
224219
{
225220
if (isFirstRow)
226221
{
@@ -232,8 +227,7 @@ await XmlReaderHelper.SkipToNextSameLevelDomAsync(reader, cancellationToken)
232227
yield return row;
233228
}
234229
}
235-
else if (!await XmlReaderHelper.SkipContentAsync(reader, cancellationToken)
236-
.ConfigureAwait(false))
230+
else if (!await XmlReaderHelper.SkipContentAsync(reader, cancellationToken).ConfigureAwait(false))
237231
{
238232
break;
239233
}
@@ -385,7 +379,7 @@ private ZipArchiveEntry GetSheetEntry(string? sheetName)
385379
: CustomPropertyHelper.GetEmptyExpandoObject(maxColumnIndex, startColumnIndex);
386380
}
387381

388-
private static void SetCellsValueAndHeaders(object? cellValue, bool useHeaderRow, Dictionary<int, string?> headRows, bool isFirstRow, IDictionary<string, object?> cell, int columnIndex)
382+
private static void SetCellsValueAndHeaders(object? cellValue, bool useHeaderRow, Dictionary<int, string> headRows, bool isFirstRow, IDictionary<string, object?> cell, int columnIndex)
389383
{
390384
if (!useHeaderRow)
391385
{
@@ -411,7 +405,7 @@ private async Task SetSharedStringsAsync(CancellationToken cancellationToken = d
411405
{
412406
cancellationToken.ThrowIfCancellationRequested();
413407

414-
if (SharedStrings is not null)
408+
if (SharedStrings is { Count: > 0 })
415409
return;
416410

417411
var sharedStringsEntry = Archive.GetEntry("xl/sharedStrings.xml");
@@ -432,7 +426,7 @@ private async Task SetSharedStringsAsync(CancellationToken cancellationToken = d
432426
SharedStrings[idx++] = sharedString;
433427
}
434428
}
435-
else if (SharedStrings is null)
429+
else if (SharedStrings is { Count: 0 })
436430
{
437431
var list = await XmlReaderHelper.GetSharedStringsAsync(stream, cancellationToken, Ns)
438432
.CreateListAsync(cancellationToken)
@@ -672,30 +666,29 @@ private void ConvertCellValue(string rawValue, string aT, int xfIndex, out objec
672666
{
673667
const NumberStyles style = NumberStyles.Any;
674668
var invariantCulture = CultureInfo.InvariantCulture;
675-
669+
value = null;
670+
676671
switch (aT)
677672
{
678673
case "s":
679674
if (int.TryParse(rawValue, style, invariantCulture, out var sstIndex))
680675
{
681676
if (sstIndex >= 0 && sstIndex < SharedStrings?.Count)
682677
{
683-
//value = Helpers.ConvertEscapeChars(_SharedStrings[sstIndex]);
684678
value = XmlHelper.DecodeString(SharedStrings[sstIndex]);
685-
return;
686679
}
687680
}
688-
value = null;
689-
return;
681+
break;
690682

691683
case "inlineStr":
692684
case "str":
693685
//TODO: it will unbox,box
694686
var v = XmlHelper.DecodeString(rawValue);
687+
value = v;
695688
if (_config.EnableConvertByteArray)
696689
{
697690
//if str start with "data:image/png;base64," then convert to byte[] https://github.com/mini-software/MiniExcel/issues/318
698-
if (v is not null && v.StartsWith("@@@fileid@@@,", StringComparison.Ordinal))
691+
if (v?.StartsWith("@@@fileid@@@,", StringComparison.Ordinal) ?? false)
699692
{
700693
var path = v[13..];
701694
var entry = Archive.GetEntry(path);
@@ -708,43 +701,25 @@ private void ConvertCellValue(string rawValue, string aT, int xfIndex, out objec
708701
}
709702
value = bytes;
710703
}
711-
else
712-
{
713-
value = v;
714-
}
715-
}
716-
else
717-
{
718-
value = v;
719704
}
720-
return;
705+
break;
721706

722707
case "b":
723708
value = rawValue == "1";
724709
return;
725710

726711
case "d":
727-
if (DateTime.TryParseExact(rawValue, "yyyy-MM-dd", invariantCulture, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out var date))
728-
{
729-
value = date;
730-
return;
731-
}
732-
733-
value = rawValue;
712+
value = DateTime.TryParseExact(rawValue, "yyyy-MM-dd", invariantCulture, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out var date)
713+
? date
714+
: rawValue;
734715
return;
735716

736717
case "e":
737718
value = rawValue;
738719
return;
739720

740721
default:
741-
if (double.TryParse(rawValue, style, invariantCulture, out var n))
742-
{
743-
value = n;
744-
return;
745-
}
746-
747-
value = rawValue;
722+
value = double.TryParse(rawValue, style, invariantCulture, out var n) ? n : rawValue;
748723
return;
749724
}
750725
}

src/MiniExcel.Core/OpenXml/OpenXmlWriter.DefaultOpenXml.cs

Lines changed: 15 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
1-
using MiniExcelLib.Core.Helpers;
21
using MiniExcelLib.Core.OpenXml.Constants;
32
using MiniExcelLib.Core.OpenXml.Models;
4-
using MiniExcelLib.Core.OpenXml.Utils;
53
using MiniExcelLib.Core.OpenXml.Zip;
6-
using MiniExcelLib.Core.Reflection;
74
using static MiniExcelLib.Core.Helpers.ImageHelper;
85

96
namespace MiniExcelLib.Core.OpenXml;
107

11-
internal partial class OpenXmlWriter : Abstractions.IMiniExcelWriter
8+
internal partial class OpenXmlWriter : IMiniExcelWriter
129
{
1310
private readonly Dictionary<string, ZipPackageInfo> _zipDictionary = [];
1411
private Dictionary<string, string> _cellXfIdMap;
@@ -202,12 +199,11 @@ private Tuple<string, string, string> GetCellValue(int rowIndex, int cellIndex,
202199

203200
if (type == typeof(byte[]) && _configuration.EnableConvertByteArray)
204201
{
202+
if (!_configuration.EnableWriteFilePath)
203+
return Tuple.Create("4", "str", "");
204+
205205
var base64 = GetFileValue(rowIndex, cellIndex, value);
206-
if (_configuration.EnableWriteFilePath)
207-
{
208-
return Tuple.Create("4", "str", XmlHelper.EncodeXml(base64));
209-
}
210-
return Tuple.Create("4", "str", "");
206+
return Tuple.Create("4", "str", XmlHelper.EncodeXml(base64));
211207
}
212208

213209
return Tuple.Create("2", "str", XmlHelper.EncodeXml(value.ToString()));
@@ -260,7 +256,7 @@ private string GetNumericValue(object value, Type type)
260256
if (type.IsAssignableFrom(typeof(float)))
261257
return ((float)value).ToString(_configuration.Culture);
262258

263-
return (decimal.Parse(value.ToString())).ToString(_configuration.Culture);
259+
return decimal.Parse(value.ToString()).ToString(_configuration.Culture);
264260
}
265261

266262
private string GetFileValue(int rowIndex, int cellIndex, object value)
@@ -272,15 +268,15 @@ private string GetFileValue(int rowIndex, int cellIndex, object value)
272268
//it can't insert to zip first to avoid cache image to memory
273269
//because sheet xml is opening.. https://github.com/mini-software/MiniExcel/issues/304#issuecomment-1017031691
274270
//int rowIndex, int cellIndex
275-
var file = new FileDto()
271+
var file = new FileDto
276272
{
277273
Byte = bytes,
278274
RowIndex = rowIndex,
279275
CellIndex = cellIndex,
280276
SheetId = _currentSheetIndex
281277
};
282278

283-
if (format != ImageHelper.ImageFormat.Unknown)
279+
if (format != ImageFormat.Unknown)
284280
{
285281
file.Extension = format.ToString();
286282
file.IsImage = true;
@@ -331,18 +327,13 @@ private static double CorrectDateTimeValue(DateTime value)
331327

332328
private static string GetDimensionRef(int maxRowIndex, int maxColumnIndex)
333329
{
334-
string dimensionRef;
335-
if (maxRowIndex == 0 && maxColumnIndex == 0)
336-
dimensionRef = "A1";
337-
else if (maxRowIndex <= 1 && maxColumnIndex == 0)
338-
dimensionRef = "A1";
339-
else if (maxColumnIndex <= 1)
340-
dimensionRef = $"A1:A{maxRowIndex}";
341-
else if (maxRowIndex == 0)
342-
dimensionRef = $"A1:{ColumnHelper.GetAlphabetColumnName(maxColumnIndex - 1)}1";
343-
else
344-
dimensionRef = $"A1:{ColumnHelper.GetAlphabetColumnName(maxColumnIndex - 1)}{maxRowIndex}";
345-
return dimensionRef;
330+
return (maxRowIndex, maxColumnIndex) switch
331+
{
332+
(<= 1, 0) => "A1",
333+
(_, <= 1) => $"A1:A{maxRowIndex}",
334+
(0, _) => $"A1:{ColumnHelper.GetAlphabetColumnName(maxColumnIndex - 1)}1",
335+
_ => $"A1:{ColumnHelper.GetAlphabetColumnName(maxColumnIndex - 1)}{maxRowIndex}"
336+
};
346337
}
347338

348339
private string GetDrawingRelationshipXml(int sheetIndex)

src/MiniExcel.Core/OpenXml/OpenXmlWriter.cs

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,15 @@
1+
using System.ComponentModel;
12
using System.Xml.Linq;
2-
using MiniExcelLib.Core.Abstractions;
3-
using MiniExcelLib.Core.Helpers;
43
using MiniExcelLib.Core.OpenXml.Constants;
54
using MiniExcelLib.Core.OpenXml.Models;
65
using MiniExcelLib.Core.OpenXml.Styles.Builder;
7-
using MiniExcelLib.Core.OpenXml.Utils;
86
using MiniExcelLib.Core.OpenXml.Zip;
9-
using MiniExcelLib.Core.Reflection;
107
using MiniExcelLib.Core.WriteAdapters;
11-
using DefaultSheetStyleBuilder = MiniExcelLib.Core.OpenXml.Styles.Builder.DefaultSheetStyleBuilder;
12-
using ISheetStyleBuilder = MiniExcelLib.Core.OpenXml.Styles.Builder.ISheetStyleBuilder;
13-
using MinimalSheetStyleBuilder = MiniExcelLib.Core.OpenXml.Styles.Builder.MinimalSheetStyleBuilder;
148
using SafeStreamWriter = MiniExcelLib.Core.Helpers.SafeStreamWriter;
159

1610
namespace MiniExcelLib.Core.OpenXml;
1711

18-
internal partial class OpenXmlWriter : Abstractions.IMiniExcelWriter
12+
internal partial class OpenXmlWriter : IMiniExcelWriter
1913
{
2014
private static readonly UTF8Encoding Utf8WithBom = new(true);
2115

@@ -35,8 +29,8 @@ internal OpenXmlWriter(Stream stream, object? value, string? sheetName, IMiniExc
3529
{
3630
_stream = stream;
3731

38-
// Why ZipArchiveMode.Update not ZipArchiveMode.Create?
39-
// R : Mode create - ZipArchiveEntry does not support seeking.'
32+
// A. Why ZipArchiveMode.Update and not ZipArchiveMode.Create?
33+
// R. ZipArchiveEntry does not support seeking when Mode is Create.
4034
_configuration = configuration as OpenXmlConfiguration ?? OpenXmlConfiguration.Default;
4135
if (_configuration is { EnableAutoWidth: true, FastMode: false })
4236
throw new InvalidOperationException("Auto width requires fast mode to be enabled");
@@ -255,13 +249,12 @@ private async Task<int> WriteValuesAsync(SafeStreamWriter writer, object values,
255249
var count = 0;
256250
var isKnownCount = writeAdapter is not null && writeAdapter.TryGetKnownCount(out count);
257251

258-
List<MiniExcelColumnInfo> props;
259252
#if SYNC_ONLY
260-
props = writeAdapter?.GetColumns();
253+
var props = writeAdapter?.GetColumns();
261254
#else
262-
props = writeAdapter is not null
263-
? writeAdapter?.GetColumns()
264-
: await asyncWriteAdapter.GetColumnsAsync().ConfigureAwait(false);
255+
var props = writeAdapter is not null
256+
? writeAdapter.GetColumns()
257+
: await (asyncWriteAdapter?.GetColumnsAsync() ?? Task.FromResult<List<MiniExcelColumnInfo>?>(null)).ConfigureAwait(false);
265258
#endif
266259

267260
if (props is null)
@@ -309,7 +302,7 @@ private async Task<int> WriteValuesAsync(SafeStreamWriter writer, object values,
309302
var currentRowIndex = 0;
310303
if (_printHeader)
311304
{
312-
await PrintHeaderAsync(writer, props, cancellationToken).ConfigureAwait(false);
305+
await PrintHeaderAsync(writer, props!, cancellationToken).ConfigureAwait(false);
313306
currentRowIndex++;
314307
}
315308

@@ -331,8 +324,6 @@ private async Task<int> WriteValuesAsync(SafeStreamWriter writer, object values,
331324
else
332325
{
333326
#if !SYNC_ONLY
334-
#pragma warning disable CA2007
335-
//todo: why does this throw compiler error even if ConfigureAwait(false) is present?
336327
await foreach (var row in asyncWriteAdapter.GetRowsAsync(props, cancellationToken).ConfigureAwait(false))
337328
{
338329
cancellationToken.ThrowIfCancellationRequested();
@@ -344,7 +335,6 @@ private async Task<int> WriteValuesAsync(SafeStreamWriter writer, object values,
344335
}
345336
await writer.WriteAsync(WorksheetXml.EndRow, cancellationToken).ConfigureAwait(false);
346337
}
347-
#pragma warning restore CA2007
348338
#endif
349339
}
350340
maxRowIndex = currentRowIndex;
@@ -518,12 +508,12 @@ private async Task GenerateStylesXmlAsync(CancellationToken cancellationToken)
518508
{
519509
cancellationToken.ThrowIfCancellationRequested();
520510

521-
using var context = new SheetStyleBuildContext(_zipDictionary, _archive, Utf8WithBom, _configuration.DynamicColumns);
522-
ISheetStyleBuilder? builder = _configuration.TableStyles switch
511+
using var context = new SheetStyleBuildContext(_zipDictionary, _archive, Utf8WithBom, _configuration.DynamicColumns ?? []);
512+
ISheetStyleBuilder builder = _configuration.TableStyles switch
523513
{
524514
TableStyles.None => new MinimalSheetStyleBuilder(context),
525515
TableStyles.Default => new DefaultSheetStyleBuilder(context, _configuration.StyleOptions),
526-
_ => null!
516+
_ => throw new InvalidEnumArgumentException(nameof(_configuration.TableStyles), (int)_configuration.TableStyles, typeof(TableStyles))
527517
};
528518

529519
var result = await builder.BuildAsync(cancellationToken).ConfigureAwait(false);

src/MiniExcel.Core/OpenXml/Picture/OpenXmlPicture.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using System.Drawing;
22
using MiniExcelLib.Core.Enums;
3-
using MiniExcelLib.Core.OpenXml.Utils;
43

54
namespace MiniExcelLib.Core.OpenXml.Picture;
65

0 commit comments

Comments
 (0)