Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions src/MiniExcel.Core/Abstractions/IMiniExcelWriteAdapter.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using MiniExcelLib.Core.Reflection;

namespace MiniExcelLib.Core.Abstractions;
namespace MiniExcelLib.Core.Abstractions;

public interface IMiniExcelWriteAdapter
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using MiniExcelLib.Core.Reflection;

namespace MiniExcelLib.Core.Abstractions;
namespace MiniExcelLib.Core.Abstractions;

public interface IMiniExcelWriteAdapterAsync
{
Expand Down
4 changes: 1 addition & 3 deletions src/MiniExcel.Core/DataReader/MiniExcelDataReaderBase.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using MiniExcelLib.Core.Abstractions;

namespace MiniExcelLib.Core.DataReader;
namespace MiniExcelLib.Core.DataReader;

/// <summary>
/// IMiniExcelDataReader Base Class
Expand Down
3 changes: 1 addition & 2 deletions src/MiniExcel.Core/OpenXml/Constants/ExcelXml.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using MiniExcelLib.Core.Helpers;
using MiniExcelLib.Core.OpenXml.Models;
using MiniExcelLib.Core.OpenXml.Models;

namespace MiniExcelLib.Core.OpenXml.Constants;

Expand Down
2 changes: 0 additions & 2 deletions src/MiniExcel.Core/OpenXml/Models/ExcelWidthCollection.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using MiniExcelLib.Core.Reflection;

namespace MiniExcelLib.Core.OpenXml.Models;

public sealed class ExcelColumnWidth
Expand Down
61 changes: 18 additions & 43 deletions src/MiniExcel.Core/OpenXml/OpenXmlReader.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
using System.Collections.ObjectModel;
using MiniExcelLib.Core.Helpers;
using MiniExcelLib.Core.OpenXml.Constants;
using MiniExcelLib.Core.OpenXml.Models;
using MiniExcelLib.Core.OpenXml.Styles;
using MiniExcelLib.Core.OpenXml.Utils;
using MiniExcelLib.Core.OpenXml.Zip;
using MiniExcelLib.Core.Reflection;
using MiniExcelMapper = MiniExcelLib.Core.Reflection.MiniExcelMapper;
using XmlReaderHelper = MiniExcelLib.Core.OpenXml.Utils.XmlReaderHelper;

namespace MiniExcelLib.Core.OpenXml;

internal partial class OpenXmlReader : Abstractions.IMiniExcelReader
internal partial class OpenXmlReader : IMiniExcelReader
{
private static readonly string[] Ns = [Schemas.SpreadsheetmlXmlns, Schemas.SpreadsheetmlXmlStrictns];
private static readonly string[] RelationshiopNs = [Schemas.SpreadsheetmlXmlRelationshipns, Schemas.SpreadsheetmlXmlStrictRelationshipns];
Expand All @@ -22,7 +19,7 @@ internal partial class OpenXmlReader : Abstractions.IMiniExcelReader
private bool _disposed;

internal readonly OpenXmlZip Archive;
internal IDictionary<int, string>? SharedStrings;
internal IDictionary<int, string> SharedStrings = new Dictionary<int, string>();

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

await foreach (var row in QueryRowAsync(reader, isFirstRow, startRowIndex, nextRowIndex,
rowIndex, startColumnIndex, endColumnIndex, maxColumnIndex,
withoutCr,
useHeaderRow, headRows, mergeCellsContext.MergeCells,
cancellationToken)
.ConfigureAwait(false))
withoutCr, useHeaderRow, headRows, mergeCellsContext.MergeCells,
cancellationToken).ConfigureAwait(false))
{
if (isFirstRow)
{
Expand All @@ -232,8 +227,7 @@ await XmlReaderHelper.SkipToNextSameLevelDomAsync(reader, cancellationToken)
yield return row;
}
}
else if (!await XmlReaderHelper.SkipContentAsync(reader, cancellationToken)
.ConfigureAwait(false))
else if (!await XmlReaderHelper.SkipContentAsync(reader, cancellationToken).ConfigureAwait(false))
{
break;
}
Expand Down Expand Up @@ -385,7 +379,7 @@ private ZipArchiveEntry GetSheetEntry(string? sheetName)
: CustomPropertyHelper.GetEmptyExpandoObject(maxColumnIndex, startColumnIndex);
}

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

if (SharedStrings is not null)
if (SharedStrings is { Count: > 0 })
return;

var sharedStringsEntry = Archive.GetEntry("xl/sharedStrings.xml");
Expand All @@ -432,7 +426,7 @@ private async Task SetSharedStringsAsync(CancellationToken cancellationToken = d
SharedStrings[idx++] = sharedString;
}
}
else if (SharedStrings is null)
else if (SharedStrings is { Count: 0 })
{
var list = await XmlReaderHelper.GetSharedStringsAsync(stream, cancellationToken, Ns)
.CreateListAsync(cancellationToken)
Expand Down Expand Up @@ -672,30 +666,29 @@ private void ConvertCellValue(string rawValue, string aT, int xfIndex, out objec
{
const NumberStyles style = NumberStyles.Any;
var invariantCulture = CultureInfo.InvariantCulture;

value = null;

switch (aT)
{
case "s":
if (int.TryParse(rawValue, style, invariantCulture, out var sstIndex))
{
if (sstIndex >= 0 && sstIndex < SharedStrings?.Count)
{
//value = Helpers.ConvertEscapeChars(_SharedStrings[sstIndex]);
value = XmlHelper.DecodeString(SharedStrings[sstIndex]);
return;
}
}
value = null;
return;
break;

case "inlineStr":
case "str":
//TODO: it will unbox,box
var v = XmlHelper.DecodeString(rawValue);
value = v;
if (_config.EnableConvertByteArray)
{
//if str start with "data:image/png;base64," then convert to byte[] https://github.com/mini-software/MiniExcel/issues/318
if (v is not null && v.StartsWith("@@@fileid@@@,", StringComparison.Ordinal))
if (v?.StartsWith("@@@fileid@@@,", StringComparison.Ordinal) ?? false)
{
var path = v[13..];
var entry = Archive.GetEntry(path);
Expand All @@ -708,43 +701,25 @@ private void ConvertCellValue(string rawValue, string aT, int xfIndex, out objec
}
value = bytes;
}
else
{
value = v;
}
}
else
{
value = v;
}
return;
break;

case "b":
value = rawValue == "1";
return;

case "d":
if (DateTime.TryParseExact(rawValue, "yyyy-MM-dd", invariantCulture, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out var date))
{
value = date;
return;
}

value = rawValue;
value = DateTime.TryParseExact(rawValue, "yyyy-MM-dd", invariantCulture, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out var date)
? date
: rawValue;
return;

case "e":
value = rawValue;
return;

default:
if (double.TryParse(rawValue, style, invariantCulture, out var n))
{
value = n;
return;
}

value = rawValue;
value = double.TryParse(rawValue, style, invariantCulture, out var n) ? n : rawValue;
return;
}
}
Expand Down
39 changes: 15 additions & 24 deletions src/MiniExcel.Core/OpenXml/OpenXmlWriter.DefaultOpenXml.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
using MiniExcelLib.Core.Helpers;
using MiniExcelLib.Core.OpenXml.Constants;
using MiniExcelLib.Core.OpenXml.Models;
using MiniExcelLib.Core.OpenXml.Utils;
using MiniExcelLib.Core.OpenXml.Zip;
using MiniExcelLib.Core.Reflection;
using static MiniExcelLib.Core.Helpers.ImageHelper;

namespace MiniExcelLib.Core.OpenXml;

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

if (type == typeof(byte[]) && _configuration.EnableConvertByteArray)
{
if (!_configuration.EnableWriteFilePath)
return Tuple.Create("4", "str", "");

var base64 = GetFileValue(rowIndex, cellIndex, value);
if (_configuration.EnableWriteFilePath)
{
return Tuple.Create("4", "str", XmlHelper.EncodeXml(base64));
}
return Tuple.Create("4", "str", "");
return Tuple.Create("4", "str", XmlHelper.EncodeXml(base64));
}

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

return (decimal.Parse(value.ToString())).ToString(_configuration.Culture);
return decimal.Parse(value.ToString()).ToString(_configuration.Culture);
}

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

if (format != ImageHelper.ImageFormat.Unknown)
if (format != ImageFormat.Unknown)
{
file.Extension = format.ToString();
file.IsImage = true;
Expand Down Expand Up @@ -331,18 +327,13 @@ private static double CorrectDateTimeValue(DateTime value)

private static string GetDimensionRef(int maxRowIndex, int maxColumnIndex)
{
string dimensionRef;
if (maxRowIndex == 0 && maxColumnIndex == 0)
dimensionRef = "A1";
else if (maxRowIndex <= 1 && maxColumnIndex == 0)
dimensionRef = "A1";
else if (maxColumnIndex <= 1)
dimensionRef = $"A1:A{maxRowIndex}";
else if (maxRowIndex == 0)
dimensionRef = $"A1:{ColumnHelper.GetAlphabetColumnName(maxColumnIndex - 1)}1";
else
dimensionRef = $"A1:{ColumnHelper.GetAlphabetColumnName(maxColumnIndex - 1)}{maxRowIndex}";
return dimensionRef;
return (maxRowIndex, maxColumnIndex) switch
{
(<= 1, 0) => "A1",
(_, <= 1) => $"A1:A{maxRowIndex}",
(0, _) => $"A1:{ColumnHelper.GetAlphabetColumnName(maxColumnIndex - 1)}1",
_ => $"A1:{ColumnHelper.GetAlphabetColumnName(maxColumnIndex - 1)}{maxRowIndex}"
};
}

private string GetDrawingRelationshipXml(int sheetIndex)
Expand Down
34 changes: 12 additions & 22 deletions src/MiniExcel.Core/OpenXml/OpenXmlWriter.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,15 @@
using System.ComponentModel;
using System.Xml.Linq;
using MiniExcelLib.Core.Abstractions;
using MiniExcelLib.Core.Helpers;
using MiniExcelLib.Core.OpenXml.Constants;
using MiniExcelLib.Core.OpenXml.Models;
using MiniExcelLib.Core.OpenXml.Styles.Builder;
using MiniExcelLib.Core.OpenXml.Utils;
using MiniExcelLib.Core.OpenXml.Zip;
using MiniExcelLib.Core.Reflection;
using MiniExcelLib.Core.WriteAdapters;
using DefaultSheetStyleBuilder = MiniExcelLib.Core.OpenXml.Styles.Builder.DefaultSheetStyleBuilder;
using ISheetStyleBuilder = MiniExcelLib.Core.OpenXml.Styles.Builder.ISheetStyleBuilder;
using MinimalSheetStyleBuilder = MiniExcelLib.Core.OpenXml.Styles.Builder.MinimalSheetStyleBuilder;
using SafeStreamWriter = MiniExcelLib.Core.Helpers.SafeStreamWriter;

namespace MiniExcelLib.Core.OpenXml;

internal partial class OpenXmlWriter : Abstractions.IMiniExcelWriter
internal partial class OpenXmlWriter : IMiniExcelWriter
{
private static readonly UTF8Encoding Utf8WithBom = new(true);

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

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

List<MiniExcelColumnInfo> props;
#if SYNC_ONLY
props = writeAdapter?.GetColumns();
var props = writeAdapter?.GetColumns();
#else
props = writeAdapter is not null
? writeAdapter?.GetColumns()
: await asyncWriteAdapter.GetColumnsAsync().ConfigureAwait(false);
var props = writeAdapter is not null
? writeAdapter.GetColumns()
: await (asyncWriteAdapter?.GetColumnsAsync() ?? Task.FromResult<List<MiniExcelColumnInfo>?>(null)).ConfigureAwait(false);
#endif

if (props is null)
Expand Down Expand Up @@ -309,7 +302,7 @@ private async Task<int> WriteValuesAsync(SafeStreamWriter writer, object values,
var currentRowIndex = 0;
if (_printHeader)
{
await PrintHeaderAsync(writer, props, cancellationToken).ConfigureAwait(false);
await PrintHeaderAsync(writer, props!, cancellationToken).ConfigureAwait(false);
currentRowIndex++;
}

Expand All @@ -331,8 +324,6 @@ private async Task<int> WriteValuesAsync(SafeStreamWriter writer, object values,
else
{
#if !SYNC_ONLY
#pragma warning disable CA2007
//todo: why does this throw compiler error even if ConfigureAwait(false) is present?
await foreach (var row in asyncWriteAdapter.GetRowsAsync(props, cancellationToken).ConfigureAwait(false))
{
cancellationToken.ThrowIfCancellationRequested();
Expand All @@ -344,7 +335,6 @@ private async Task<int> WriteValuesAsync(SafeStreamWriter writer, object values,
}
await writer.WriteAsync(WorksheetXml.EndRow, cancellationToken).ConfigureAwait(false);
}
#pragma warning restore CA2007
#endif
}
maxRowIndex = currentRowIndex;
Expand Down Expand Up @@ -518,12 +508,12 @@ private async Task GenerateStylesXmlAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

using var context = new SheetStyleBuildContext(_zipDictionary, _archive, Utf8WithBom, _configuration.DynamicColumns);
ISheetStyleBuilder? builder = _configuration.TableStyles switch
using var context = new SheetStyleBuildContext(_zipDictionary, _archive, Utf8WithBom, _configuration.DynamicColumns ?? []);
ISheetStyleBuilder builder = _configuration.TableStyles switch
{
TableStyles.None => new MinimalSheetStyleBuilder(context),
TableStyles.Default => new DefaultSheetStyleBuilder(context, _configuration.StyleOptions),
_ => null!
_ => throw new InvalidEnumArgumentException(nameof(_configuration.TableStyles), (int)_configuration.TableStyles, typeof(TableStyles))
};

var result = await builder.BuildAsync(cancellationToken).ConfigureAwait(false);
Expand Down
1 change: 0 additions & 1 deletion src/MiniExcel.Core/OpenXml/Picture/OpenXmlPicture.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.Drawing;
using MiniExcelLib.Core.Enums;
using MiniExcelLib.Core.OpenXml.Utils;

namespace MiniExcelLib.Core.OpenXml.Picture;

Expand Down
Loading
Loading