Методы расширения для парсинга excel файлов

This commit is contained in:
Степанов Дмитрий 2024-02-07 07:40:00 +03:00
parent fa28fdfefe
commit b686834236
3 changed files with 191 additions and 82 deletions

View File

@ -53,7 +53,7 @@
<PackageReference Include="AsbSaubReportLas" Version="3.24.116.510" />
<PackageReference Include="AsbSaubReportPdf" Version="3.24.116.510" />
<PackageReference Include="CliWrap" Version="3.6.6" />
<PackageReference Include="ClosedXML" Version="0.97.0" />
<PackageReference Include="ClosedXML" Version="0.102.2" />
<PackageReference Include="itext7" Version="8.0.2" />
<PackageReference Include="itext7.bouncy-castle-adapter" Version="8.0.2" />
<PackageReference Include="Mapster" Version="7.4.0" />

View File

@ -1,96 +1,46 @@
using ClosedXML.Excel;
using System;
using System.Globalization;
using System.IO;
using System.Linq;
namespace AsbCloudInfrastructure;
internal static class XLExtentions
public static class XLExtentions
{
internal static IXLCell _SetValue(this IXLCell cell, DateTime value, string dateFormat = "DD.MM.YYYY HH:MM:SS", bool setAllBorders = true)
{
cell.Value = value;
if (setAllBorders == true)
{
cell.Style
.SetAllBorders()
.Alignment.WrapText = true;
}
public static IXLWorksheet GetWorksheet(this IXLWorkbook workbook, string sheetName) =>
workbook.Worksheets.FirstOrDefault(ws => string.Equals(ws.Name.Trim(), sheetName.Trim(), StringComparison.CurrentCultureIgnoreCase))
?? throw new FileFormatException($"Книга excel не содержит листа {sheetName}.");
public static IXLCell SetCellValue<T>(this IXLCell cell, T value)
{
if (typeof(T) == typeof(DateTime))
cell.Style.DateFormat.Format = "DD.MM.YYYY HH:MM:SS";
cell.Value = value;
cell.Value = XLCellValue.FromObject(value);
cell.DataType = XLDataType.DateTime;
cell.Style.DateFormat.Format = "DD.MM.YYYY HH:MM:SS";
return cell;
}
return cell;
}
public static IXLCell SetHyperlink(this IXLCell cell, string link)
{
cell.SetHyperlink(new XLHyperlink(link));
public static IXLCell SetVal(this IXLCell cell, double? value, string format = "0.00")
{
cell.Value = (value is not null && double.IsFinite(value.Value)) ? value : null;
cell.DataType = XLDataType.Number;
cell.Style.NumberFormat.Format = format;
return cell;
}
return cell;
}
public static IXLCell SetVal(this IXLCell cell, string value, bool adaptRowHeight = false)
{
cell.Value = value;
if (adaptRowHeight)
{
var colWidth = cell.WorksheetColumn().Width;
var maxCharsToWrap = colWidth / (0.1d * cell.Style.Font.FontSize);
if (value.Length > maxCharsToWrap)
{
var row = cell.WorksheetRow();
var baseHeight = row.Height;
row.Height = 0.5d * baseHeight * Math.Ceiling(1d + value.Length / maxCharsToWrap);
}
}
public static T? GetCellValue<T>(this IXLCell cell)
{
try
{
if (cell.IsEmpty() && default(T) == null)
return default;
return cell;
}
public static IXLCell SetVal(this IXLCell cell, DateTime value, string dateFormat = "DD.MM.YYYY HH:MM:SS")
{
cell.Value = value;
cell.DataType = XLDataType.DateTime;
cell.Style.DateFormat.Format = dateFormat;
return cell;
}
private static IXLStyle SetAllBorders(this IXLStyle style, XLBorderStyleValues borderStyle = XLBorderStyleValues.Thin)
{
style.Border.RightBorder = borderStyle;
style.Border.LeftBorder = borderStyle;
style.Border.TopBorder = borderStyle;
style.Border.BottomBorder = borderStyle;
style.Border.InsideBorder = borderStyle;
style.Border.OutsideBorder = borderStyle;
return style;
}
internal static T? GetCellValue<T>(this IXLCell cell)
{
try
{
if (cell.IsEmpty() && default(T) == null)
return default;
if (typeof(T) != typeof(DateTime))
return (T)Convert.ChangeType(cell.GetFormattedString(), typeof(T), CultureInfo.InvariantCulture);
if (cell.Value is DateTime dateTime)
return (T)(object)dateTime;
return (T)(object)DateTime.FromOADate((double)cell.Value);
}
catch
{
throw new FileFormatException(
$"Лист '{cell.Worksheet.Name}'. {cell.Address.RowNumber} строка содержит некорректное значение в {cell.Address.ColumnNumber} столбце");
}
}
return cell.GetValue<T>();
}
catch
{
throw new FileFormatException(
$"Лист '{cell.Worksheet.Name}'. {cell.Address.RowNumber} строка содержит некорректное значение в {cell.Address.ColumnNumber} столбце");
}
}
}

View File

@ -0,0 +1,159 @@
using System;
using AsbCloudInfrastructure;
using ClosedXML.Excel;
using Xunit;
namespace AsbCloudWebApi.Tests;
public class XLExtensionsTests
{
private const string cellUsed = "A1";
private const string sheetName = "test";
private readonly IXLWorkbook workbook;
public XLExtensionsTests()
{
workbook = new XLWorkbook();
workbook.Worksheets.Add(sheetName);
}
[Fact]
public void GetWorksheet_returns_sheet()
{
//act
var sheet = workbook.GetWorksheet(sheetName);
//assert
Assert.NotNull(sheet);
}
[Theory]
[MemberData(nameof(valueTypesToSet))]
public void SetCellValue_returns_success(object value, XLDataType expectedDataType)
{
//act
var cell = GetCell(cellUsed);
cell.SetCellValue(value);
//assert
Assert.Equal(expectedDataType, cell.DataType);
}
[Fact]
public void GetCellValue_returns_double()
{
//arrange
const double expectedValue = 2.0d;
SetCellValue(expectedValue);
//act
var actualValue = GetCell(cellUsed).GetCellValue<double>();
//assert
Assert.Equal(expectedValue, actualValue);
}
[Fact]
public void GetCellValue_returns_float()
{
//arrange
const float expectedValue = 2.0f;
SetCellValue(expectedValue);
//act
var actualValue = GetCell(cellUsed).GetCellValue<float>();
//assert
Assert.Equal(expectedValue, actualValue);
}
[Theory]
[InlineData("test")]
[InlineData(null)]
public void GetCellValue_returns_string(string? expectedValue)
{
//arrange
SetCellValue(expectedValue);
//act
var actualValue = GetCell(cellUsed).GetCellValue<string>();
//assert
Assert.Equal(expectedValue, actualValue);
}
[Fact]
public void GetCellValue_returns_bool()
{
//arrange
const bool expectedValue = true;
SetCellValue(expectedValue);
//act
var actualValue = GetCell(cellUsed).GetCellValue<bool>();
//assert
Assert.Equal(expectedValue, actualValue);
}
[Fact]
public void GetCellValue_returns_dateTime()
{
//arrange
var expectedValue = DateTime.Parse("2023-01-01");
SetCellValue(expectedValue);
//act
var actualValue = GetCell(cellUsed).GetCellValue<DateTime>();
//assert
Assert.Equal(expectedValue, actualValue);
Assert.Equal(DateTimeKind.Unspecified, actualValue.Kind);
}
[Fact]
public void GetCellValue_returns_nullable()
{
//act
var actualValue = GetCell(cellUsed).GetCellValue<object?>();
//assert
Assert.Null(actualValue);
}
[Fact]
public void SetHyperlink_returns_success()
{
//arrange
const string link = "http://test.ru";
//act
GetCell(cellUsed).SetHyperlink(link);
//assert
var hyperLink = GetCell(cellUsed).GetHyperlink();
Assert.NotNull(hyperLink);
}
private void SetCellValue<T>(T value)
{
var cell = GetCell(cellUsed);
cell.SetCellValue(value);
}
public static readonly object[][] valueTypesToSet =
{
new object[] { 2.0d, XLDataType.Number },
new object[] { 2.0f, XLDataType.Number },
new object[] { "test", XLDataType.Text },
new object[] { true, XLDataType.Boolean },
new object[] { DateTime.UtcNow, XLDataType.DateTime }
};
private IXLCell GetCell(string cellAddressInRange)
{
var sheet = workbook.GetWorksheet(sheetName);
return sheet.Cell(cellAddressInRange);
}
}