Вынес метод получения значения в метод расширения

This commit is contained in:
parent 7ae00fe2f7
commit 0b95361b69
6 changed files with 218 additions and 263 deletions

View File

@ -1,161 +0,0 @@
using ClosedXML.Excel;
using System;
namespace AsbCloudInfrastructure.Services.DailyReport
{
internal static class XLExtentions
{
public static IXLRange _SetValue(this IXLRange range, object value)
{
var mergedRange = range.Merge();
mergedRange.FirstCell()._SetValue(value);
var colWidth = mergedRange.FirstCell().WorksheetColumn().Width;
var maxCharsToWrap = colWidth / (0.1d * mergedRange.FirstCell().Style.Font.FontSize);
if (value is string valueString && valueString.Length > maxCharsToWrap)
{
var row = mergedRange.FirstCell().WorksheetRow();
var baseHeight = row.Height;
row.Height = 0.5d * baseHeight * Math.Ceiling(1d + valueString.Length / maxCharsToWrap);
}
mergedRange.Style.SetAllBorders()
.Alignment.SetWrapText(true);
return mergedRange;
}
public static IXLCell _SetValue(this IXLCell cell, object value)
{
switch (value)
{
case DateTime dateTime:
cell._SetValue(dateTime);
break;
case IFormattable formattable:
cell._SetValue(formattable);
break;
case string valueString:
cell._SetValue(valueString);
break;
default:
cell.Value = value;
break;
}
return cell;
}
public static IXLCell _SetValue(this IXLCell cell, string value, bool adaptRowHeight = false)
{
cell.Value = value;
cell.Style
.SetAllBorders()
.Alignment.WrapText = true;
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);
}
}
return cell;
}
public static IXLCell _ValueNoBorder(this IXLCell cell, string value, bool adaptRowHeight = false)
{
cell.Value = value;
cell.Style.Alignment.WrapText = true;
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);
}
}
return cell;
}
public static IXLCell _SetValue(this IXLCell cell, DateTime value, string dateFormat = "DD.MM.YYYY HH:MM:SS")
{
cell.Value = value;
cell.Style
.SetAllBorders()
.Alignment.WrapText = true;
cell.Value = value;
cell.DataType = XLDataType.DateTime;
cell.Style.DateFormat.Format = "DD.MM.YYYY HH:MM:SS";
return cell;
}
public static IXLCell _SetValue(this IXLCell cell, IFormattable value, string format = "0.00")
{
cell.Value = value;
cell.Style
.SetAllBorders()
.Alignment.WrapText = true;
cell.Value = value;
cell.DataType = XLDataType.Number;
cell.Style.NumberFormat.Format = "0.00";
return cell;
}
public 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;
}
public static IXLStyle SetBaseFont(this IXLStyle style)
{
style.Font.FontName = "Calibri";
style.Font.FontSize = 10;
return style;
}
public static IXLStyle SetH1(this IXLStyle style)
{
style.Font.FontName = "Calibri";
style.Font.FontSize = 14;
return style;
}
/// <summary>
/// Костыль исправляющий проблему в библиотеке IXLRange Range(this IXLWorksheet, IXLAddress, IXLAddress) с кастингом IXLAddress к XLAddress.
/// </summary>
/// <param name="sheet"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <returns></returns>
public static IXLRange _Range(this IXLWorksheet sheet, CellAddress begin, CellAddress end)
=> sheet.Range(begin.RowNumber, begin.ColumnNumber, end.RowNumber, end.ColumnNumber);
}
}

View File

@ -187,23 +187,23 @@ public class ProcessMapPlanImportService : IProcessMapPlanImportService
private ProcessMapPlanDto ParseRow(IXLRow row)
{
var wellSectionTypeCaption = GetCellValue<string>(row, columnWellSectionType).Trim().ToLower();
var modeName = GetCellValue<string>(row, columnMode).Trim().ToLower();
var depthStart = GetCellValue<double>(row, columnDepthStart);
var depthEnd = GetCellValue<double>(row, columnDepthEnd);
var pressurePlan = GetCellValue<double>(row, columnPressurePlan);
var pressureLimitMax = GetCellValue<double>(row, columnPressureLimitMax);
var axialLoadPlan = GetCellValue<double>(row, columnAxialLoadPlan);
var axialLoadLimitMax = GetCellValue<double>(row, columnAxialLoadLimitMax);
var topDriveTorquePlan = GetCellValue<double>(row, columnTopDriveTorquePlan);
var topDriveTorqueLimitMax = GetCellValue<double>(row, columnTopDriveTorqueLimitMax);
var topDriveSpeedPlan = GetCellValue<double>(row, columnTopDriveSpeedPlan);
var topDriveSpeedLimitMax = GetCellValue<double>(row, columnTopDriveSpeedLimitMax);
var flowPlan = GetCellValue<double>(row, columnFlowPlan);
var flowLimitMax = GetCellValue<double>(row, columnFlowLimitMax);
var ropPlan = GetCellValue<double>(row, columnRopPlan);
var usageSaub = GetCellValue<double>(row, columnUsageSaub);
var usageSpin = GetCellValue<double>(row, columnUsageSpin);
var wellSectionTypeCaption = row.Cell(columnWellSectionType).GetCellValue<string>().Trim().ToLower();
var modeName = row.Cell(columnMode).GetCellValue<string>().Trim().ToLower();
var depthStart = row.Cell(columnDepthStart).GetCellValue<double>();
var depthEnd = row.Cell(columnDepthEnd).GetCellValue<double>();
var pressurePlan = row.Cell(columnPressurePlan).GetCellValue<double>();
var pressureLimitMax = row.Cell(columnPressureLimitMax).GetCellValue<double>();
var axialLoadPlan = row.Cell(columnAxialLoadPlan).GetCellValue<double>();
var axialLoadLimitMax = row.Cell(columnAxialLoadLimitMax).GetCellValue<double>();
var topDriveTorquePlan = row.Cell(columnTopDriveTorquePlan).GetCellValue<double>();
var topDriveTorqueLimitMax = row.Cell(columnTopDriveTorqueLimitMax).GetCellValue<double>();
var topDriveSpeedPlan = row.Cell(columnTopDriveSpeedPlan).GetCellValue<double>();
var topDriveSpeedLimitMax = row.Cell(columnTopDriveSpeedLimitMax).GetCellValue<double>();
var flowPlan = row.Cell(columnFlowPlan).GetCellValue<double>();
var flowLimitMax = row.Cell(columnFlowLimitMax).GetCellValue<double>();
var ropPlan = row.Cell(columnRopPlan).GetCellValue<double>();
var usageSaub = row.Cell(columnUsageSaub).GetCellValue<double>();
var usageSpin = row.Cell(columnUsageSpin).GetCellValue<double>();
var wellSection = sections.FirstOrDefault(s => s.Caption.Trim().ToLower() == wellSectionTypeCaption)
?? throw new FileFormatException(
@ -342,19 +342,4 @@ public class ProcessMapPlanImportService : IProcessMapPlanImportService
2 => "Слайд",
_ => "Ручной",
};
//TODO: вынести в метод расширения
private static T GetCellValue<T>(IXLRow row, int columnNumber)
{
try
{
var cell = row.Cell(columnNumber);
return (T)Convert.ChangeType(cell.Value, typeof(T));
}
catch
{
throw new FileFormatException(
$"Лист {row.Worksheet.Name}. Ячейка: ({row.RowNumber()},{columnNumber}) содержит некорректное значение");
}
}
}

View File

@ -177,32 +177,18 @@ namespace AsbCloudInfrastructure.Services.Trajectory
private TrajectoryGeoPlanDto ParseRow(IXLRow row)
{
var _wellboreDepth = row.Cell(ColumnWellboreDepth).Value;
var _zenithAngle = row.Cell(ColumnZenithAngle).Value;
var _azimuthGeo = row.Cell(ColumnAzimuthGeo).Value;
var _azimuthMagnetic = row.Cell(ColumnAzimuthMagnetic).Value;
var _verticalDepth = row.Cell(ColumnVerticalDepth).Value;
var _radius = row.Cell(ColumnRadius).Value;
var _comment = row.Cell(ColumnComment).Value;
var trajectoryRow = new TrajectoryGeoPlanDto();
static double getDoubleValue(object value, string nameParam, IXLRow row)
var trajectoryRow = new TrajectoryGeoPlanDto
{
if (value is double _value)
return _value;
throw new FileFormatException($"Лист {row.Worksheet.Name}. Строка {row.RowNumber()} - некорректные данные - {nameParam}");
}
trajectoryRow.WellboreDepth = getDoubleValue(_wellboreDepth, "Глубина по стволу", row);
trajectoryRow.ZenithAngle = getDoubleValue(_zenithAngle, "Зенитный угол", row);
trajectoryRow.AzimuthGeo = getDoubleValue(_azimuthGeo, "Азимут географический", row);
trajectoryRow.AzimuthMagnetic = getDoubleValue(_azimuthMagnetic, "Азимут магнитный", row);
trajectoryRow.VerticalDepth = getDoubleValue(_verticalDepth, "Глубина вертикальная", row);
trajectoryRow.Radius = getDoubleValue(_radius, "Радиус цели", row);
if (_comment is not null)
trajectoryRow.Comment = _comment.ToString();
WellboreDepth = row.Cell(ColumnWellboreDepth).GetCellValue<double>(),
ZenithAngle = row.Cell(ColumnZenithAngle).GetCellValue<double>(),
AzimuthGeo = row.Cell(ColumnAzimuthGeo).GetCellValue<double>(),
AzimuthMagnetic = row.Cell(ColumnAzimuthMagnetic).GetCellValue<double>(),
VerticalDepth = row.Cell(ColumnVerticalDepth).GetCellValue<double>(),
Radius = row.Cell(ColumnRadius).GetCellValue<double>(),
Comment = row.Cell(ColumnComment).IsEmpty() ? null :
row.Cell(ColumnComment).GetCellValue<string>()
};
return trajectoryRow;
}
}

View File

@ -79,28 +79,14 @@ public class WellOperationDefaultExcelParser : IWellOperationExcelParser
return new RowDto
{
Number = xlRow.RowNumber(),
Section = GetCellValue<string>(xlRow.Cell(DefaultTemplateInfo.ColumnSection)),
Category = GetCellValue<string>(xlRow.Cell(DefaultTemplateInfo.ColumnCategory)),
CategoryInfo = GetCellValue<string>(xlRow.Cell(DefaultTemplateInfo.ColumnCategoryInfo)),
DepthStart = GetCellValue<double>(xlRow.Cell(DefaultTemplateInfo.ColumnDepthStart)),
DepthEnd = GetCellValue<double>(xlRow.Cell(DefaultTemplateInfo.ColumnDepthEnd)),
Date = GetCellValue<DateTime>(xlRow.Cell(DefaultTemplateInfo.ColumnDate)),
Duration = GetCellValue<double>(xlRow.Cell(DefaultTemplateInfo.ColumnDuration)),
Comment = GetCellValue<string>(xlRow.Cell(DefaultTemplateInfo.ColumnComment))
Section = xlRow.Cell(DefaultTemplateInfo.ColumnSection).GetCellValue<string>(),
Category = xlRow.Cell(DefaultTemplateInfo.ColumnCategory).GetCellValue<string>(),
CategoryInfo = xlRow.Cell(DefaultTemplateInfo.ColumnCategoryInfo).GetCellValue<string>(),
DepthStart = xlRow.Cell(DefaultTemplateInfo.ColumnDepthStart).GetCellValue<double>(),
DepthEnd = xlRow.Cell(DefaultTemplateInfo.ColumnDepthEnd).GetCellValue<double>(),
Date = xlRow.Cell(DefaultTemplateInfo.ColumnDate).GetCellValue<DateTime>(),
Duration = xlRow.Cell(DefaultTemplateInfo.ColumnDuration).GetCellValue<double>(),
Comment = xlRow.Cell(DefaultTemplateInfo.ColumnComment).GetCellValue<string>()
};
}
//TODO: вынести в метод расширения
private static T GetCellValue<T>(IXLCell cell)
{
try
{
return (T)Convert.ChangeType(cell.Value, typeof(T));
}
catch
{
throw new FileFormatException(
$"Лист '{cell.Worksheet.Name}'. Ячейка: ({cell.Address.RowNumber},{cell.Address.ColumnNumber}) содержит некорректное значение");
}
}
}

View File

@ -97,11 +97,11 @@ public class WellOperationGazpromKhantosExcelParser : IWellOperationExcelParser
operations.Add(new Operation
{
RowNumber = xlRow.RowNumber(),
CategoryInfo = GetCellValue<string>(xlRow.Cell(operationAttributes[OperationAttributes.CategoryInfo])),
SectionDiameter = GetCellValue<double>(xlRow.Cell(operationAttributes[OperationAttributes.SectionDiameter])),
Depth = GetCellValue<double>(xlRow.Cell(operationAttributes[OperationAttributes.Depth])),
Duration = GetCellValue<double>(xlRow.Cell(operationAttributes[OperationAttributes.Duration])),
Date = GetCellValue<DateTime>(xlRow.Cell(operationAttributes[OperationAttributes.Date]))
CategoryInfo = xlRow.Cell(operationAttributes[OperationAttributes.CategoryInfo]).GetCellValue<string>(),
SectionDiameter =xlRow.Cell(operationAttributes[OperationAttributes.SectionDiameter]).GetCellValue<double>(),
Depth = xlRow.Cell(operationAttributes[OperationAttributes.Depth]).GetCellValue<double>(),
Duration = xlRow.Cell(operationAttributes[OperationAttributes.Duration]).GetCellValue<double>(),
Date = xlRow.Cell(operationAttributes[OperationAttributes.Date]).GetCellValue<DateTime>()
});
}
catch (FileFormatException ex)
@ -183,7 +183,7 @@ public class WellOperationGazpromKhantosExcelParser : IWellOperationExcelParser
foreach (var cell in cells)
{
var operationAttribute = GetValueDictionary(operationAttributesDict, GetCellValue<string>(cell), 0.7);
var operationAttribute = GetValueDictionary(operationAttributesDict, cell.GetCellValue<string>(), 0.7);
if (operationAttribute is null || operationAttributes.Any(a => a.Key == operationAttribute))
continue;
@ -234,21 +234,4 @@ public class WellOperationGazpromKhantosExcelParser : IWellOperationExcelParser
.Select(line => line.Split(separator))
.ToDictionary(parts => parts[0].Trim(), parts => parts[1].Trim());
}
//TODO: вынести в метод расширения
private static T GetCellValue<T>(IXLCell cell)
{
try
{
if (typeof(T) != typeof(DateTime))
return (T)Convert.ChangeType(cell.GetFormattedString(), typeof(T), CultureInfo.InvariantCulture);
return (T)(object)DateTime.FromOADate((double)cell.Value);
}
catch
{
throw new FileFormatException(
$"Лист '{cell.Worksheet.Name}'. Ячейка: ({cell.Address.RowNumber},{cell.Address.ColumnNumber}) содержит некорректное значение");
}
}
}

View File

@ -0,0 +1,176 @@
using ClosedXML.Excel;
using System;
using System.Globalization;
using System.IO;
using AsbCloudInfrastructure.Services.DailyReport;
namespace AsbCloudInfrastructure;
internal static class XLExtentions
{
internal static IXLRange _SetValue(this IXLRange range, object value)
{
var mergedRange = range.Merge();
mergedRange.FirstCell()._SetValue(value);
var colWidth = mergedRange.FirstCell().WorksheetColumn().Width;
var maxCharsToWrap = colWidth / (0.1d * mergedRange.FirstCell().Style.Font.FontSize);
if (value is string valueString && valueString.Length > maxCharsToWrap)
{
var row = mergedRange.FirstCell().WorksheetRow();
var baseHeight = row.Height;
row.Height = 0.5d * baseHeight * Math.Ceiling(1d + valueString.Length / maxCharsToWrap);
}
mergedRange.Style.SetAllBorders()
.Alignment.SetWrapText(true);
return mergedRange;
}
internal static IXLCell _SetValue(this IXLCell cell, object value)
{
switch (value)
{
case DateTime dateTime:
cell._SetValue(dateTime);
break;
case IFormattable formattable:
cell._SetValue(formattable);
break;
case string valueString:
cell._SetValue(valueString);
break;
default:
cell.Value = value;
break;
}
return cell;
}
internal static IXLCell _SetValue(this IXLCell cell, string value, bool adaptRowHeight = false)
{
cell.Value = value;
cell.Style
.SetAllBorders()
.Alignment.WrapText = true;
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);
}
}
return cell;
}
internal static IXLCell _ValueNoBorder(this IXLCell cell, string value, bool adaptRowHeight = false)
{
cell.Value = value;
cell.Style.Alignment.WrapText = true;
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);
}
}
return cell;
}
internal static IXLCell _SetValue(this IXLCell cell, DateTime value, string dateFormat = "DD.MM.YYYY HH:MM:SS")
{
cell.Value = value;
cell.Style
.SetAllBorders()
.Alignment.WrapText = true;
cell.Value = value;
cell.DataType = XLDataType.DateTime;
cell.Style.DateFormat.Format = "DD.MM.YYYY HH:MM:SS";
return cell;
}
internal static IXLCell _SetValue(this IXLCell cell, IFormattable value, string format = "0.00")
{
cell.Value = value;
cell.Style
.SetAllBorders()
.Alignment.WrapText = true;
cell.Value = value;
cell.DataType = XLDataType.Number;
cell.Style.NumberFormat.Format = "0.00";
return cell;
}
internal 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 IXLStyle SetBaseFont(this IXLStyle style)
{
style.Font.FontName = "Calibri";
style.Font.FontSize = 10;
return style;
}
internal static IXLStyle SetH1(this IXLStyle style)
{
style.Font.FontName = "Calibri";
style.Font.FontSize = 14;
return style;
}
/// <summary>
/// Костыль исправляющий проблему в библиотеке IXLRange Range(this IXLWorksheet, IXLAddress, IXLAddress) с кастингом IXLAddress к XLAddress.
/// </summary>
/// <param name="sheet"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <returns></returns>
internal static IXLRange _Range(this IXLWorksheet sheet, CellAddress begin, CellAddress end)
=> sheet.Range(begin.RowNumber, begin.ColumnNumber, end.RowNumber, end.ColumnNumber);
internal static T GetCellValue<T>(this IXLCell cell)
{
try
{
if (typeof(T) != typeof(DateTime))
return (T)Convert.ChangeType(cell.GetFormattedString(), typeof(T), CultureInfo.InvariantCulture);
return (T)(object)DateTime.FromOADate((double)cell.Value);
}
catch
{
throw new FileFormatException(
$"Лист '{cell.Worksheet.Name}'. Ячейка: ({cell.Address.RowNumber},{cell.Address.ColumnNumber}) содержит некорректное значение");
}
}
}