Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
shps951023 committed Feb 20, 2025
2 parents 94e59f9 + b7f7816 commit 1021b08
Show file tree
Hide file tree
Showing 12 changed files with 186 additions and 89 deletions.
Binary file added samples/xlsx/TestUriMapping.xlsx
Binary file not shown.
39 changes: 16 additions & 23 deletions src/MiniExcel/OpenXml/ExcelOpenXmlSheetReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -322,12 +322,11 @@ public IEnumerable<IDictionary<string, object>> Query(bool useHeaderRow, string
{
_mergeCells.MergesValues[aR] = cellValue;
}
else if (_mergeCells.MergesMap.ContainsKey(aR))
else if (_mergeCells.MergesMap.TryGetValue(aR, out var mergeKey))
{
var mergeKey = _mergeCells.MergesMap[aR];
object mergeValue = null;
if (_mergeCells.MergesValues.ContainsKey(mergeKey))
mergeValue = _mergeCells.MergesValues[mergeKey];
if (_mergeCells.MergesValues.TryGetValue(mergeKey, out var value))
mergeValue = value;
cellValue = mergeValue;
}
}
Expand Down Expand Up @@ -398,9 +397,8 @@ private void SetCellsValueAndHeaders(object cellValue, bool useHeaderRow, ref Di
}
else
{
if (headRows.ContainsKey(columnIndex))
if (headRows.TryGetValue(columnIndex, out var key))
{
var key = headRows[columnIndex];
cell[key] = cellValue;
}
}
Expand Down Expand Up @@ -467,10 +465,9 @@ private void SetCellsValueAndHeaders(object cellValue, bool useHeaderRow, ref Di
{
foreach (var alias in pInfo.ExcelColumnAliases)
{
if (headersDic.ContainsKey(alias))
if (headersDic.TryGetValue(alias, out var columnId))
{
object newV = null;
var columnId = headersDic[alias];
var columnName = keys[columnId];
item.TryGetValue(columnName, out var itemValue);

Expand All @@ -490,9 +487,8 @@ private void SetCellsValueAndHeaders(object cellValue, bool useHeaderRow, ref Di
{
item.TryGetValue(pInfo.ExcelIndexName, out itemValue);
}
else if (headersDic.ContainsKey(pInfo.ExcelColumnName))
else if (headersDic.TryGetValue(pInfo.ExcelColumnName, out var columnId))
{
var columnId = headersDic[pInfo.ExcelColumnName];
var columnName = keys[columnId];
item.TryGetValue(columnName, out itemValue);
}
Expand Down Expand Up @@ -822,7 +818,7 @@ public IEnumerable<IDictionary<string, object>> QueryRange(bool useHeaderRow, st
// if sheets count > 1 need to read xl/_rels/workbook.xml.rels
var sheets = _archive.entries.Where(w => w.FullName.StartsWith("xl/worksheets/sheet", StringComparison.OrdinalIgnoreCase)
|| w.FullName.StartsWith("/xl/worksheets/sheet", StringComparison.OrdinalIgnoreCase)
);
).ToList();
ZipArchiveEntry sheetEntry = null;
if (sheetName != null)
{
Expand All @@ -832,7 +828,7 @@ public IEnumerable<IDictionary<string, object>> QueryRange(bool useHeaderRow, st
throw new InvalidOperationException("Please check sheetName/Index is correct");
sheetEntry = sheets.Single(w => w.FullName == $"xl/{s.Path}" || w.FullName == $"/xl/{s.Path}" || w.FullName == s.Path || s.Path == $"/{w.FullName}");
}
else if (sheets.Count() > 1)
else if (sheets.Count > 1)
{
SetWorkbookRels(_archive.entries);
var s = _sheetRecords[0];
Expand Down Expand Up @@ -1086,13 +1082,9 @@ public IEnumerable<IDictionary<string, object>> QueryRange(bool useHeaderRow, st
{
_mergeCells.MergesValues[aR] = cellValue;
}
else if (_mergeCells.MergesMap.ContainsKey(aR))
else if (_mergeCells.MergesMap.TryGetValue(aR, out var mergeKey))
{
var mergeKey = _mergeCells.MergesMap[aR];
object mergeValue = null;
if (_mergeCells.MergesValues.ContainsKey(mergeKey))
mergeValue = _mergeCells.MergesValues[mergeKey];
cellValue = mergeValue;
_mergeCells.MergesValues.TryGetValue(mergeKey, out cellValue);
}
}
////2022-09-24跳过endcell结束单元格所以在的列
Expand Down Expand Up @@ -1194,15 +1186,16 @@ public IEnumerable<IDictionary<string, object>> QueryRange(bool useHeaderRow, st
{
foreach (var alias in pInfo.ExcelColumnAliases)
{
if (headersDic.ContainsKey(alias))
if (headersDic.TryGetValue(alias, out var value))
{
object newV = null;
object itemValue = item[keys[headersDic[alias]]];
object itemValue = item[keys[value]];

if (itemValue == null)
continue;

newV = TypeHelper.TypeMapping(v, pInfo, newV, itemValue, rowIndex, startCell, configuration);
newV = TypeHelper.TypeMapping(v, pInfo, newV, itemValue, rowIndex, startCell,
configuration);
}
}
}
Expand All @@ -1213,8 +1206,8 @@ public IEnumerable<IDictionary<string, object>> QueryRange(bool useHeaderRow, st
object itemValue = null;
if (pInfo.ExcelIndexName != null && keys.Contains(pInfo.ExcelIndexName))
itemValue = item[pInfo.ExcelIndexName];
else if (headersDic.ContainsKey(pInfo.ExcelColumnName))
itemValue = item[keys[headersDic[pInfo.ExcelColumnName]]];
else if (headersDic.TryGetValue(pInfo.ExcelColumnName, out var value))
itemValue = item[keys[value]];

if (itemValue == null)
continue;
Expand Down
20 changes: 10 additions & 10 deletions src/MiniExcel/OpenXml/ExcelOpenXmlSheetWriter.Async.cs
Original file line number Diff line number Diff line change
Expand Up @@ -325,16 +325,7 @@ private async Task WriteCellAsync(MiniExcelAsyncStreamWriter writer, string cell

private async Task WriteCellAsync(MiniExcelAsyncStreamWriter writer, int rowIndex, int cellIndex, object value, ExcelColumnInfo p, ExcelWidthCollection widthCollection)
{
var columnReference = ExcelOpenXmlUtils.ConvertXyToCell(cellIndex, rowIndex);
var valueIsNull = value is null || value is DBNull;

if (_configuration.EnableWriteNullValueCell && valueIsNull)
{
await writer.WriteAsync(WorksheetXml.EmptyCell(columnReference, GetCellXfId("2")));
return;
}

if (p.CustomFormatter != null)
if (p?.CustomFormatter != null)
{
try
{
Expand All @@ -346,6 +337,15 @@ private async Task WriteCellAsync(MiniExcelAsyncStreamWriter writer, int rowInde
}
}

var columnReference = ExcelOpenXmlUtils.ConvertXyToCell(cellIndex, rowIndex);
var valueIsNull = value is null || value is DBNull;

if (_configuration.EnableWriteNullValueCell && valueIsNull)
{
await writer.WriteAsync(WorksheetXml.EmptyCell(columnReference, GetCellXfId("2")));
return;
}

var tuple = GetCellValue(rowIndex, cellIndex, value, p, valueIsNull);

var styleIndex = tuple.Item1;
Expand Down
18 changes: 9 additions & 9 deletions src/MiniExcel/OpenXml/ExcelOpenXmlSheetWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -325,15 +325,6 @@ private void PrintHeader(MiniExcelStreamWriter writer, List<ExcelColumnInfo> pro

private void WriteCell(MiniExcelStreamWriter writer, int rowIndex, int cellIndex, object value, ExcelColumnInfo columnInfo, ExcelWidthCollection widthCollection)
{
var columnReference = ExcelOpenXmlUtils.ConvertXyToCell(cellIndex, rowIndex);
var valueIsNull = value is null || value is DBNull;

if (_configuration.EnableWriteNullValueCell && valueIsNull)
{
writer.Write(WorksheetXml.EmptyCell(columnReference, GetCellXfId("2")));
return;
}

if (columnInfo?.CustomFormatter != null)
{
try
Expand All @@ -346,6 +337,15 @@ private void WriteCell(MiniExcelStreamWriter writer, int rowIndex, int cellIndex
}
}

var columnReference = ExcelOpenXmlUtils.ConvertXyToCell(cellIndex, rowIndex);
var valueIsNull = value is null || value is DBNull || (_configuration.WriteEmptyStringAsNull && value is String && value == string.Empty);

Check warning on line 341 in src/MiniExcel/OpenXml/ExcelOpenXmlSheetWriter.cs

View workflow job for this annotation

GitHub Actions / build

Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'

Check warning on line 341 in src/MiniExcel/OpenXml/ExcelOpenXmlSheetWriter.cs

View workflow job for this annotation

GitHub Actions / build

Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'

Check warning on line 341 in src/MiniExcel/OpenXml/ExcelOpenXmlSheetWriter.cs

View workflow job for this annotation

GitHub Actions / build

Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'

if (_configuration.EnableWriteNullValueCell && valueIsNull)
{
writer.Write(WorksheetXml.EmptyCell(columnReference, GetCellXfId("2")));
return;
}

var tuple = GetCellValue(rowIndex, cellIndex, value, columnInfo, valueIsNull);

var styleIndex = tuple.Item1; // https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.spreadsheet.cell?view=openxml-3.0.1
Expand Down
1 change: 1 addition & 0 deletions src/MiniExcel/OpenXml/OpenXmlConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public class OpenXmlConfiguration : Configuration
public bool EnableConvertByteArray { get; set; } = true;
public bool IgnoreTemplateParameterMissing { get; set; } = true;
public bool EnableWriteNullValueCell { get; set; } = true;
public bool WriteEmptyStringAsNull { get; set; } = false;
public bool EnableSharedStringCache { get; set; } = true;
public long SharedStringCacheSize { get; set; } = 5 * 1024 * 1024;
public DynamicExcelSheet[] DynamicSheets { get; set; }
Expand Down
32 changes: 16 additions & 16 deletions src/MiniExcel/SaveByTemplate/ExcelOpenXmlTemplate.Impl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -482,9 +482,8 @@ private void WriteSheetXml(Stream stream, XmlDocument doc, XmlNode sheetData, bo
rowXml.Replace(key, "");
continue;
}
if (!dic.ContainsKey(propInfo.Key))
if (!dic.TryGetValue(propInfo.Key, out var cellValue))
continue;
var cellValue = dic[propInfo.Key];
if (cellValue == null)
{
rowXml.Replace(key, "");
Expand Down Expand Up @@ -899,9 +898,9 @@ private void ReplaceSharedStringsToStr(IDictionary<int, string> sharedStrings, r
if (t == "s")
{
//need to check sharedstring exist or not
if (sharedStrings.ContainsKey(int.Parse(v.InnerText)))
if (sharedStrings.TryGetValue(int.Parse(v.InnerText), out var shared))
{
v.InnerText = sharedStrings[int.Parse(v.InnerText)];
v.InnerText = shared;
// change type = str and replace its value
c.SetAttribute("t", "str");
}
Expand Down Expand Up @@ -935,11 +934,11 @@ private void UpdateDimensionAndGetRowsInfo(IDictionary<string, object> inputMaps
var r = c.GetAttribute("r");

// ==== mergecells ====
if (this.XMergeCellInfos.ContainsKey(r))
if (this.XMergeCellInfos.TryGetValue(r, out var merCell))
{
if (xRowInfo.RowMercells == null)
xRowInfo.RowMercells = new List<XMergeCell>();
xRowInfo.RowMercells.Add(this.XMergeCellInfos[r]);
xRowInfo.RowMercells.Add(merCell);
}

if (changeRowIndex)
Expand All @@ -962,7 +961,7 @@ private void UpdateDimensionAndGetRowsInfo(IDictionary<string, object> inputMaps
continue;

// TODO: default if not contain property key, clean the template string
if (!inputMaps.ContainsKey(propNames[0]))
if (!inputMaps.TryGetValue(propNames[0], out var cellValue))
{
if (_configuration.IgnoreTemplateParameterMissing)
{
Expand All @@ -975,19 +974,21 @@ private void UpdateDimensionAndGetRowsInfo(IDictionary<string, object> inputMaps
}
}

var cellValue = inputMaps[propNames[0]]; // 1. From left to right, only the first set is used as the basis for the list
if ((cellValue is IEnumerable || cellValue is IList<object>) && !(cellValue is string))
//cellValue = inputMaps[propNames[0]] - 1. From left to right, only the first set is used as the basis for the list
if (cellValue is IEnumerable && !(cellValue is string))
{
if (this.XMergeCellInfos.ContainsKey(r))
if (xRowInfo.IEnumerableMercell == null)
{
if (xRowInfo.IEnumerableMercell == null)
if (this.XMergeCellInfos.TryGetValue(r, out var info))
{
xRowInfo.IEnumerableMercell = this.XMergeCellInfos[r];
xRowInfo.IEnumerableMercell = info;
}
}

xRowInfo.CellIEnumerableValues = cellValue as IEnumerable;
xRowInfo.CellIlListValues = cellValue as IList<object>;
xRowInfo.CellIlListValues = cellValue is IList<object> ?
cellValue as IList<object> :
xRowInfo.CellIEnumerableValues.Cast<object>().ToList();

// get ienumerable runtime type
if (xRowInfo.IEnumerableGenricType == null) //avoid duplicate to add rowindexdiff ![image](https://user-images.githubusercontent.com/12729184/114851348-522ac000-9e14-11eb-8244-4730754d6885.png)
Expand Down Expand Up @@ -1063,14 +1064,13 @@ private void UpdateDimensionAndGetRowsInfo(IDictionary<string, object> inputMaps
v.InnerText = v.InnerText.Replace($"{{{{{propNames[0]}}}}}", propNames[1]);
break;
}
if (!xRowInfo.PropsMap.ContainsKey(propNames[1]))
if (!xRowInfo.PropsMap.TryGetValue(propNames[1], out var prop))
{
v.InnerText = v.InnerText.Replace($"{{{{{propNames[0]}.{propNames[1]}}}}}", "");
continue;
throw new InvalidDataException($"{propNames[0]} doesn't have {propNames[1]} property");
}
// auto check type https://github.com/shps951023/MiniExcel/issues/177
var prop = xRowInfo.PropsMap[propNames[1]];
var type = prop.UnderlyingTypePropType; //avoid nullable

if (isMultiMatch)
Expand Down Expand Up @@ -1283,4 +1283,4 @@ private static bool EvaluateStatement(object tagValue, string comparisonOperator
return checkStatement;
}
}
}
}
Loading

0 comments on commit 1021b08

Please sign in to comment.