Usings simplify

This commit is contained in:
Sergey Chebotar 2023-03-28 10:36:36 +03:00
parent 2280b49ae1
commit cdb153c988
10 changed files with 390 additions and 437 deletions

View File

@ -1,56 +1,48 @@
using ExcelDna.Integration; namespace RhSolutions.AddIn;
using Microsoft.Extensions.DependencyInjection;
using RhSolutions.Models;
using RhSolutions.Services;
using System.Collections.Generic;
using System.Linq;
namespace RhSolutions.AddIn public class RhSolutionsFunction
{ {
public class RhSolutionsFunction [ExcelFunction(Description = "Распознать артикул и попробовать найти его в прайс-листе")]
public static object RHSOLUTIONS([ExcelArgument(Name = "\"Строка с названием материала\"")] string line)
{ {
[ExcelFunction(Description = "Распознать артикул и попробовать найти его в прайс-листе")] IDatabaseClient databaseClient = RhSolutionsAddIn.ServiceProvider.GetService<IDatabaseClient>();
public static object RHSOLUTIONS([ExcelArgument(Name = "\"Строка с названием материала\"")] string line) IEnumerable<Product> requestResult = ExcelAsyncUtil.Run("Database request", line, delegate
{ {
IDatabaseClient databaseClient = RhSolutionsAddIn.ServiceProvider.GetService<IDatabaseClient>(); return databaseClient.GetProducts(line)
IEnumerable<Product> requestResult = ExcelAsyncUtil.Run("Database request", line, delegate .GetAwaiter()
{ .GetResult();
return databaseClient.GetProducts(line) }) as IEnumerable<Product>;
.GetAwaiter()
.GetResult();
}) as IEnumerable<Product>;
Sku.TryParse(line, out var skus); Sku.TryParse(line, out var skus);
if (requestResult == null) if (requestResult == null)
{
if (skus.Count() > 0)
{ {
if (skus.Count() > 0) return $"{skus.First()} ...";
{ }
return $"{skus.First()} ..."; else
} {
else return "Загрузка...";
{ }
return "Загрузка..."; }
}
else
{
if (requestResult.Count() == 0 && skus.Count() == 0)
{
return ExcelError.ExcelErrorNA;
}
else if (requestResult.Count() == 0)
{
return $"{skus.First()}";
} }
else else
{ {
if (requestResult.Count() == 0 && skus.Count() == 0) var firstProduct = requestResult.First();
{ return $"{firstProduct.ProductSku} {firstProduct.Name}";
return ExcelError.ExcelErrorNA;
}
else if (requestResult.Count() == 0)
{
return $"{skus.First()}";
}
else
{
var firstProduct = requestResult.First();
return $"{firstProduct.ProductSku} {firstProduct.Name}";
}
} }
} }
} }

View File

@ -1,66 +1,59 @@
using Microsoft.Office.Interop.Excel; using RhSolutions.AddIn;
using RhSolutions.AddIn;
using RhSolutions.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using Range = Microsoft.Office.Interop.Excel.Range;
namespace RhSolutions.Controllers namespace RhSolutions.Controllers;
internal class CombineTool : ToolBase
{ {
internal class CombineTool : ToolBase private List<SourcePriceList> SourceFiles { get; set; }
public CombineTool()
{ {
private List<SourcePriceList> SourceFiles { get; set; } var dialog = RhSolutionsAddIn.Excel.FileDialog[Microsoft.Office.Core.MsoFileDialogType.msoFileDialogFilePicker];
dialog.AllowMultiSelect = true;
dialog.Filters.Add("Файлы Excel", "*.xls; *.xlsx; *.xlsm");
public CombineTool() if (dialog.Show() < 0)
{ {
var dialog = RhSolutionsAddIn.Excel.FileDialog[Microsoft.Office.Core.MsoFileDialogType.msoFileDialogFilePicker]; List<string> files = new();
dialog.AllowMultiSelect = true;
dialog.Filters.Add("Файлы Excel", "*.xls; *.xlsx; *.xlsm");
if (dialog.Show() < 0) foreach (string file in dialog.SelectedItems)
{ {
List<string> files = new(); files.Add(file);
foreach (string file in dialog.SelectedItems)
{
files.Add(file);
}
SourceFiles = SourcePriceList.GetSourceLists(files.ToArray());
} }
else SourceFiles = SourcePriceList.GetSourceLists(files.ToArray());
{
throw new Exception("Не выбраны файлы");
}
} }
public override void FillTarget() else
{ {
using (ProgressBar = new ProgressBar("Заполняю строки...", SourceFiles.Sum(file => file.PositionAmount.Count))) throw new Exception("Не выбраны файлы");
using (ResultBar = new ResultBar()) }
}
public override void FillTarget()
{
using (ProgressBar = new ProgressBar("Заполняю строки...", SourceFiles.Sum(file => file.PositionAmount.Count)))
using (ResultBar = new ResultBar())
{
foreach (SourcePriceList source in SourceFiles)
{ {
foreach (SourcePriceList source in SourceFiles) TargetFile.Sheet.Columns[TargetFile.AmountCell.Column]
.EntireColumn
.Insert(XlInsertShiftDirection.xlShiftToRight, XlInsertFormatOrigin.xlFormatFromRightOrBelow);
Range newColumnHeader = TargetFile.Sheet.Cells[TargetFile.AmountCell.Row, TargetFile.AmountCell.Column - 1];
newColumnHeader.Value2 = $"{source.Name}";
newColumnHeader.WrapText = true;
foreach (var kvp in source.PositionAmount)
{ {
TargetFile.Sheet.Columns[TargetFile.AmountCell.Column] FillPositionAmountToColumns(kvp, TargetFile.AmountCell.Column - 1, TargetFile.AmountCell.Column);
.EntireColumn ProgressBar.Update();
.Insert(XlInsertShiftDirection.xlShiftToRight, XlInsertFormatOrigin.xlFormatFromRightOrBelow);
Range newColumnHeader = TargetFile.Sheet.Cells[TargetFile.AmountCell.Row, TargetFile.AmountCell.Column - 1];
newColumnHeader.Value2 = $"{source.Name}";
newColumnHeader.WrapText = true;
foreach (var kvp in source.PositionAmount)
{
FillPositionAmountToColumns(kvp, TargetFile.AmountCell.Column - 1, TargetFile.AmountCell.Column);
ProgressBar.Update();
}
} }
FilterByAmount();
ResultBar.Update();
} }
FilterByAmount();
ResultBar.Update();
} }
} }
} }

View File

@ -1,30 +1,27 @@
using RhSolutions.Models; namespace RhSolutions.Controllers;
namespace RhSolutions.Controllers internal class ConvertTool : ToolBase
{ {
internal class ConvertTool : ToolBase private SourcePriceList Current { get; set; }
public ConvertTool()
{ {
private SourcePriceList Current { get; set; } Current = new SourcePriceList(ExcelApp.ActiveWorkbook);
}
public ConvertTool() public override void FillTarget()
{
using (ProgressBar = new ProgressBar("Заполняю строки...", Current.PositionAmount.Count))
using (ResultBar = new ResultBar())
{ {
Current = new SourcePriceList(ExcelApp.ActiveWorkbook); foreach (var kvp in Current.PositionAmount)
}
public override void FillTarget()
{
using (ProgressBar = new ProgressBar("Заполняю строки...", Current.PositionAmount.Count))
using (ResultBar = new ResultBar())
{ {
foreach (var kvp in Current.PositionAmount) FillPositionAmountToColumns(kvp, TargetFile.AmountCell.Column);
{ ProgressBar.Update();
FillPositionAmountToColumns(kvp, TargetFile.AmountCell.Column);
ProgressBar.Update();
}
FilterByAmount();
ResultBar.Update();
} }
FilterByAmount();
ResultBar.Update();
} }
} }
} }

View File

@ -1,99 +1,95 @@
using Microsoft.Office.Interop.Excel; using RhSolutions.Models;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using RhSolutions.Models;
using System.Linq; using System.Linq;
using Range = Microsoft.Office.Interop.Excel.Range;
namespace RhSolutions.Controllers namespace RhSolutions.Controllers;
internal class ExportTool : ToolBase
{ {
internal class ExportTool : ToolBase private Dictionary<Product, double> PositionAmount;
private readonly Range Selection;
public ExportTool()
{ {
private Dictionary<Product, double> PositionAmount; Selection = ExcelApp.Selection;
private readonly Range Selection; GetSelected();
public ExportTool() if (PositionAmount.Count == 0)
{ {
Selection = ExcelApp.Selection; throw new Exception("В выделенном диапазоне не найдены позиции для экспорта");
GetSelected();
if (PositionAmount.Count == 0)
{
throw new Exception("В выделенном диапазоне не найдены позиции для экспорта");
}
} }
}
public override void FillTarget() public override void FillTarget()
{
using (ProgressBar = new ProgressBar("Заполняю строки...", PositionAmount.Count))
using (ResultBar = new ResultBar())
{ {
using (ProgressBar = new ProgressBar("Заполняю строки...", PositionAmount.Count)) foreach (var kvp in PositionAmount)
using (ResultBar = new ResultBar())
{ {
foreach (var kvp in PositionAmount) FillPositionAmountToColumns(kvp, TargetFile.AmountCell.Column);
{ ProgressBar.Update();
FillPositionAmountToColumns(kvp, TargetFile.AmountCell.Column);
ProgressBar.Update();
}
FilterByAmount();
ResultBar.Update();
} }
FilterByAmount();
ResultBar.Update();
} }
}
private void GetSelected() private void GetSelected()
{
object[,] cells = Selection.Value2;
PositionAmount = new Dictionary<Product, double>();
int rowsCount = Selection.Rows.Count;
for (int row = 1; row <= rowsCount; row++)
{ {
object[,] cells = Selection.Value2; if (cells[row, 1] == null || cells[row, 2] == null)
PositionAmount = new Dictionary<Product, double>(); continue;
int rowsCount = Selection.Rows.Count; string sku = null;
double? amount = null;
for (int row = 1; row <= rowsCount; row++) for (int column = 1; column <= 2; column++)
{ {
if (cells[row, 1] == null || cells[row, 2] == null) object current = cells[row, column];
continue;
string sku = null; if (Sku.TryParse(current.ToString(), out var rauSku))
double? amount = null;
for (int column = 1; column <= 2; column++)
{ {
object current = cells[row, column]; sku = rauSku.FirstOrDefault().ToString() ?? null;
if (Sku.TryParse(current.ToString(), out var rauSku))
{
sku = rauSku.FirstOrDefault().ToString() ?? null;
}
else if (current.GetType() == typeof(string)
&& double.TryParse(current.ToString(), out _))
{
amount = double.Parse((string)current);
}
else if (current.GetType() == typeof(double))
{
amount = (double)current;
}
} }
if (sku == null || amount == null) else if (current.GetType() == typeof(string)
&& double.TryParse(current.ToString(), out _))
{ {
continue; amount = double.Parse((string)current);
} }
Product position = new Product else if (current.GetType() == typeof(double))
{ {
ProductSku = sku amount = (double)current;
};
if (PositionAmount.ContainsKey(position))
{
PositionAmount[position] += amount.Value;
} }
}
else if (sku == null || amount == null)
{ {
PositionAmount.Add(position, amount.Value); continue;
} }
Product position = new Product
{
ProductSku = sku
};
if (PositionAmount.ContainsKey(position))
{
PositionAmount[position] += amount.Value;
}
else
{
PositionAmount.Add(position, amount.Value);
} }
} }
} }

View File

@ -1,23 +1,19 @@
using ExcelDna.Integration.CustomUI; using ExcelDna.Integration.CustomUI;
using Microsoft.Office.Interop.Excel;
using RhSolutions.AddIn; using RhSolutions.AddIn;
using RhSolutions.Services;
using System;
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows.Forms; using System.Windows.Forms;
using Range = Microsoft.Office.Interop.Excel.Range;
namespace RhSolutions.Controllers namespace RhSolutions.Controllers;
[ComVisible(true)]
public class RibbonController : ExcelRibbon
{ {
[ComVisible(true)] private static IRibbonUI ribbonUi;
public class RibbonController : ExcelRibbon
{
private static IRibbonUI ribbonUi;
public override string GetCustomUI(string RibbonID) public override string GetCustomUI(string RibbonID)
{ {
return @" return @"
<customUI onLoad='RibbonLoad' xmlns='http://schemas.microsoft.com/office/2006/01/customui'> <customUI onLoad='RibbonLoad' xmlns='http://schemas.microsoft.com/office/2006/01/customui'>
<ribbon> <ribbon>
<tabs> <tabs>
@ -37,96 +33,95 @@ namespace RhSolutions.Controllers
</tabs> </tabs>
</ribbon> </ribbon>
</customUI>"; </customUI>";
} }
public void RibbonLoad(IRibbonUI sender) public void RibbonLoad(IRibbonUI sender)
{
ribbonUi = sender;
}
public static void RefreshControl(string id)
{
if (ribbonUi != null)
{ {
ribbonUi = sender; ribbonUi.InvalidateControl(id);
}
public static void RefreshControl(string id)
{
if (ribbonUi != null)
{
ribbonUi.InvalidateControl(id);
}
}
public void OnSetPricePressed(IRibbonControl control)
{
var dialog = RhSolutionsAddIn.Excel
.FileDialog[Microsoft.Office.Core.MsoFileDialogType.msoFileDialogFilePicker];
dialog.AllowMultiSelect = false;
dialog.Filters.Add("Файлы Excel", "*.xls; *.xlsx; *.xlsm");
if (dialog.Show() < 0)
{
RhSolutionsAddIn.Configuration.SetPriceListPath(dialog.SelectedItems.Item(1));
RhSolutionsAddIn.Configuration.SaveSettings();
}
}
public void OnToolPressed(IRibbonControl control)
{
try
{
ToolBase tool = control.Id switch
{
"export" => new ExportTool(),
"convert" => new ConvertTool(),
"merge" => new MergeTool(),
"combine" => new CombineTool(),
_ => throw new Exception("Неизвестный инструмент"),
};
tool.OpenNewPrice();
tool.FillTarget();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message,
"Ошибка",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
RhSolutionsAddIn.Excel.StatusBar = false;
return;
}
}
public bool GetConvertEnabled(IRibbonControl control)
{
if (RhSolutionsAddIn.Excel.ActiveWorkbook == null)
return false;
else
{
Worksheet worksheet = RhSolutionsAddIn.Excel.ActiveWorkbook.ActiveSheet;
return worksheet.IsRehauSource();
}
}
public bool GetExportEnabled(IRibbonControl control)
{
if (RhSolutionsAddIn.Excel.ActiveWorkbook == null)
return false;
else
{
Range selection = RhSolutionsAddIn.Excel.Selection;
return selection.Columns.Count == 2;
}
}
public string GetVersionLabel(IRibbonControl control)
{
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
return $"v{version}";
}
public string GetPriceListPathLabel(IRibbonControl control)
{
string name = RhSolutionsAddIn.Configuration.GetPriceListFileName();
return string.IsNullOrEmpty(name) ? "Нет файла шаблона!" : name;
} }
} }
public void OnSetPricePressed(IRibbonControl control)
{
var dialog = RhSolutionsAddIn.Excel
.FileDialog[Microsoft.Office.Core.MsoFileDialogType.msoFileDialogFilePicker];
dialog.AllowMultiSelect = false;
dialog.Filters.Add("Файлы Excel", "*.xls; *.xlsx; *.xlsm");
if (dialog.Show() < 0)
{
RhSolutionsAddIn.Configuration.SetPriceListPath(dialog.SelectedItems.Item(1));
RhSolutionsAddIn.Configuration.SaveSettings();
}
}
public void OnToolPressed(IRibbonControl control)
{
try
{
ToolBase tool = control.Id switch
{
"export" => new ExportTool(),
"convert" => new ConvertTool(),
"merge" => new MergeTool(),
"combine" => new CombineTool(),
_ => throw new Exception("Неизвестный инструмент"),
};
tool.OpenNewPrice();
tool.FillTarget();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message,
"Ошибка",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
RhSolutionsAddIn.Excel.StatusBar = false;
return;
}
}
public bool GetConvertEnabled(IRibbonControl control)
{
if (RhSolutionsAddIn.Excel.ActiveWorkbook == null)
return false;
else
{
Worksheet worksheet = RhSolutionsAddIn.Excel.ActiveWorkbook.ActiveSheet;
return worksheet.IsRehauSource();
}
}
public bool GetExportEnabled(IRibbonControl control)
{
if (RhSolutionsAddIn.Excel.ActiveWorkbook == null)
return false;
else
{
Range selection = RhSolutionsAddIn.Excel.Selection;
return selection.Columns.Count == 2;
}
}
public string GetVersionLabel(IRibbonControl control)
{
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
return $"v{version}";
}
public string GetPriceListPathLabel(IRibbonControl control)
{
string name = RhSolutionsAddIn.Configuration.GetPriceListFileName();
return string.IsNullOrEmpty(name) ? "Нет файла шаблона!" : name;
}
} }

View File

@ -1,11 +1,4 @@
using Microsoft.Office.Interop.Excel; using RhSolutions.AddIn;
using RhSolutions.AddIn;
using RhSolutions.Models;
using RhSolutions.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using Range = Microsoft.Office.Interop.Excel.Range;
namespace RhSolutions.Controllers namespace RhSolutions.Controllers
{ {

View File

@ -1,113 +1,106 @@
using ExcelDna.Integration; using System.IO;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Range = Microsoft.Office.Interop.Excel.Range;
namespace RhSolutions.Models namespace RhSolutions.Models;
internal class SourcePriceList : PriceListBase
{ {
internal class SourcePriceList : PriceListBase public Dictionary<Product, double> PositionAmount { get; private set; }
public SourcePriceList(Workbook workbook)
{ {
public Dictionary<Product, double> PositionAmount { get; private set; } if (workbook == null)
public SourcePriceList(Workbook workbook)
{ {
if (workbook == null) throw new ArgumentException($"Нет рабочего файла");
{
throw new ArgumentException($"Нет рабочего файла");
}
Sheet = workbook.ActiveSheet;
Name = Path.GetFileNameWithoutExtension(workbook.FullName);
Range[] cells = new[]
{
AmountCell = Sheet.Cells.Find(PriceListHeaders.Amount),
SkuCell = Sheet.Cells.Find(PriceListHeaders.Sku),
GroupCell = Sheet.Cells.Find(PriceListHeaders.Group),
NameCell = Sheet.Cells.Find(PriceListHeaders.Name)
};
if (cells.Any(x => x == null))
{
throw new ArgumentException($"Файл {Name} не распознан");
}
CreatePositionsDict();
} }
public static List<SourcePriceList> GetSourceLists(string[] files) Sheet = workbook.ActiveSheet;
Name = Path.GetFileNameWithoutExtension(workbook.FullName);
Range[] cells = new[]
{ {
var ExcelApp = (Application)ExcelDnaUtil.Application; AmountCell = Sheet.Cells.Find(PriceListHeaders.Amount),
ProgressBar bar = new ProgressBar("Открываю исходные файлы...", files.Length); SkuCell = Sheet.Cells.Find(PriceListHeaders.Sku),
GroupCell = Sheet.Cells.Find(PriceListHeaders.Group),
NameCell = Sheet.Cells.Find(PriceListHeaders.Name)
};
List<SourcePriceList> sourceFiles = new List<SourcePriceList>(); if (cells.Any(x => x == null))
{
foreach (string file in files) throw new ArgumentException($"Файл {Name} не распознан");
{
ExcelApp.ScreenUpdating = false;
Workbook wb = ExcelApp.Workbooks.Open(file);
try
{
SourcePriceList priceList = new SourcePriceList(wb);
sourceFiles.Add(priceList);
wb.Close();
bar.Update();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show
(ex.Message,
"Ошибка открытия исходного прайс-листа",
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Information);
wb.Close();
bar.Update();
}
ExcelApp.ScreenUpdating = true;
}
return sourceFiles;
} }
private void CreatePositionsDict() CreatePositionsDict();
}
public static List<SourcePriceList> GetSourceLists(string[] files)
{
var ExcelApp = (Application)ExcelDnaUtil.Application;
ProgressBar bar = new ProgressBar("Открываю исходные файлы...", files.Length);
List<SourcePriceList> sourceFiles = new List<SourcePriceList>();
foreach (string file in files)
{ {
PositionAmount = new Dictionary<Product, double>(); ExcelApp.ScreenUpdating = false;
Workbook wb = ExcelApp.Workbooks.Open(file);
for (int row = AmountCell.Row + 1; row <= Sheet.Cells[Sheet.Rows.Count, AmountCell.Column].End[XlDirection.xlUp].Row; row++) try
{ {
double? amount = Sheet.Cells[row, AmountCell.Column].Value2 as double?; SourcePriceList priceList = new SourcePriceList(wb);
sourceFiles.Add(priceList);
wb.Close();
bar.Update();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show
(ex.Message,
"Ошибка открытия исходного прайс-листа",
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Information);
wb.Close();
bar.Update();
}
ExcelApp.ScreenUpdating = true;
}
if (amount != null && amount.Value != 0) return sourceFiles;
}
private void CreatePositionsDict()
{
PositionAmount = new Dictionary<Product, double>();
for (int row = AmountCell.Row + 1; row <= Sheet.Cells[Sheet.Rows.Count, AmountCell.Column].End[XlDirection.xlUp].Row; row++)
{
double? amount = Sheet.Cells[row, AmountCell.Column].Value2 as double?;
if (amount != null && amount.Value != 0)
{
object group = Sheet.Cells[row, GroupCell.Column].Value2;
object name = Sheet.Cells[row, NameCell.Column].Value2;
object sku = Sheet.Cells[row, SkuCell.Column].Value2;
if (group == null || name == null || sku == null)
continue;
if (!Sku.TryParse(sku.ToString(), out _))
continue;
Product p = new Product
{ {
object group = Sheet.Cells[row, GroupCell.Column].Value2; ProductSku = sku.ToString(),
object name = Sheet.Cells[row, NameCell.Column].Value2; ProductLine = group.ToString(),
object sku = Sheet.Cells[row, SkuCell.Column].Value2; Name = name.ToString()
};
if (group == null || name == null || sku == null) if (PositionAmount.ContainsKey(p))
continue; {
PositionAmount[p] += amount.Value;
}
if (!Sku.TryParse(sku.ToString(), out _)) else
continue; {
PositionAmount.Add(p, amount.Value);
Product p = new Product
{
ProductSku = sku.ToString(),
ProductLine = group.ToString(),
Name = name.ToString()
};
if (PositionAmount.ContainsKey(p))
{
PositionAmount[p] += amount.Value;
}
else
{
PositionAmount.Add(p, amount.Value);
}
} }
} }
} }

View File

@ -1,40 +1,35 @@
using Microsoft.Office.Interop.Excel; using System.IO;
using System;
using System.IO;
using System.Linq;
using Range = Microsoft.Office.Interop.Excel.Range;
namespace RhSolutions.Models namespace RhSolutions.Models;
internal class TargetPriceList : PriceListBase
{ {
internal class TargetPriceList : PriceListBase public Range OldSkuCell { get; private set; }
public TargetPriceList(Workbook workbook)
{ {
public Range OldSkuCell { get; private set; } if (workbook == null)
public TargetPriceList(Workbook workbook)
{ {
if (workbook == null) throw new ArgumentException("Невозможно открыть книгу шаблонного файла. " +
{ "Возможно открыт файл с именем, совпадающим с именем шаблонного файла.");
throw new ArgumentException("Невозможно открыть книгу шаблонного файла. " + }
"Возможно открыт файл с именем, совпадающим с именем шаблонного файла.");
}
Sheet = workbook.ActiveSheet; Sheet = workbook.ActiveSheet;
Name = Path.GetFileNameWithoutExtension(workbook.FullName); Name = Path.GetFileNameWithoutExtension(workbook.FullName);
Range[] cells = new[] Range[] cells = new[]
{ {
AmountCell = Sheet.Cells.Find(PriceListHeaders.Amount), AmountCell = Sheet.Cells.Find(PriceListHeaders.Amount),
SkuCell = Sheet.Cells.Find(PriceListHeaders.Sku), SkuCell = Sheet.Cells.Find(PriceListHeaders.Sku),
GroupCell = Sheet.Cells.Find(PriceListHeaders.Group), GroupCell = Sheet.Cells.Find(PriceListHeaders.Group),
NameCell = Sheet.Cells.Find(PriceListHeaders.Name) NameCell = Sheet.Cells.Find(PriceListHeaders.Name)
}; };
OldSkuCell = Sheet.Cells.Find(PriceListHeaders.OldSku); OldSkuCell = Sheet.Cells.Find(PriceListHeaders.OldSku);
if (cells.Any(x => x == null)) if (cells.Any(x => x == null))
{ {
throw new ArgumentException($"Шаблон {Name} не является прайс-листом"); throw new ArgumentException($"Шаблон {Name} не является прайс-листом");
}
} }
} }
} }

View File

@ -1,40 +1,35 @@
using Microsoft.Office.Interop.Excel; namespace RhSolutions.Services;
using RhSolutions.Models;
using System.Linq;
namespace RhSolutions.Services public static class WorksheetExtensions
{ {
public static class WorksheetExtensions public static bool IsRehauSource(this Worksheet worksheet)
{ {
public static bool IsRehauSource(this Worksheet worksheet) Range amountCell;
Range skuCell;
Range groupCell;
Range nameCell;
Range[] cells = new[]
{ {
Range amountCell; amountCell = worksheet.Cells.Find(PriceListHeaders.Amount),
Range skuCell; skuCell = worksheet.Cells.Find(PriceListHeaders.Sku),
Range groupCell; groupCell = worksheet.Cells.Find(PriceListHeaders.Group),
Range nameCell; nameCell = worksheet.Cells.Find(PriceListHeaders.Name)
};
Range[] cells = new[] return cells.All(x => x != null);
{ }
amountCell = worksheet.Cells.Find(PriceListHeaders.Amount),
skuCell = worksheet.Cells.Find(PriceListHeaders.Sku),
groupCell = worksheet.Cells.Find(PriceListHeaders.Group),
nameCell = worksheet.Cells.Find(PriceListHeaders.Name)
};
return cells.All(x => x != null); public static void AddValue(this Range range, double value)
{
if (range.Value2 == null)
{
range.Value2 = value;
} }
public static void AddValue(this Range range, double value) else
{ {
if (range.Value2 == null) range.Value2 += value;
{
range.Value2 = value;
}
else
{
range.Value2 += value;
}
} }
} }
} }

View File

@ -1,5 +1,9 @@
global using ExcelDna.Integration; global using ExcelDna.Integration;
global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Office.Interop.Excel; global using Microsoft.Office.Interop.Excel;
global using RhSolutions.Models;
global using RhSolutions.Services; global using RhSolutions.Services;
global using System; global using System;
global using System.Collections.Generic;
global using System.Linq;
global using Range = Microsoft.Office.Interop.Excel.Range;