using ClosedXML.Excel; using System; using System.IO; using System.Linq; namespace AsbCloudInfrastructure; public static class XLExtentions { public const string ProblemDetailsTemplate = "Лист: {0}, Строка: {1}, Столбец: {2}. {3}"; public const string NotFoundSheetTemplate = "Книга excel не содержит листа {0}"; public const string InvalidValueTemplate = "Лист: {0}, Строка: {1}, Столбец: {2}. Содержит некорректное значение"; 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(string.Format(NotFoundSheetTemplate, sheetName)); public static IXLCell SetCellValue(this IXLCell cell, T value, string? format = null) { if (typeof(T) == typeof(DateTime)) { cell.Style.DateFormat.Format = format ?? "DD.MM.YYYY HH:MM:SS"; } cell.Value = XLCellValue.FromObject(value); return cell; } public static IXLCell SetHyperlink(this IXLCell cell, string link) { cell.SetHyperlink(new XLHyperlink(link)); return cell; } public static T? GetCellValue(this IXLCell cell) { try { if (cell.IsEmpty() && default(T) == null) return default; return cell.GetValue(); } catch { var message = string.Format(InvalidValueTemplate, cell.Worksheet.Name, cell.Address.RowNumber, cell.Address.ColumnNumber); throw new FileFormatException(message); } } }