Compare commits

...

10 Commits

Author SHA1 Message Date
Sergey Chebotar
a6caea1787 Ignore new line symbol in names 2023-04-20 09:31:27 +03:00
Sergey Chebotar
f0ec240f35 Add Measure field to reading-writing 2023-04-20 07:18:16 +03:00
Sergey Chebotar
13996f0381 Change internal Product class to nuget library 2023-04-20 06:58:27 +03:00
Sergey Chebotar
8e820c4cd9 Add dxfNet library to xll package 2023-04-20 06:34:54 +03:00
Sergey Chebotar
4fb498138a Implement Dxf Writer 2023-04-19 21:04:13 +03:00
Sergey Chebotar
e295709e65 Dxf export button activation fix 2023-04-17 08:49:26 +03:00
Sergey Chebotar
b6254b1565 Add Tool factory 2023-04-14 08:08:46 +03:00
Sergey Chebotar
3f4d7f45b7 Delete Excel.Extensions 2023-04-07 09:26:52 +03:00
Sergey Chebotar
6acba1a542 Add Dxf Export button 2023-04-07 08:10:51 +03:00
Sergey Chebotar
56a32cd567 Add DxfTool 2023-04-07 08:10:28 +03:00
28 changed files with 653 additions and 493 deletions

View File

@ -20,11 +20,18 @@ public sealed class RhSolutionsAddIn : IExcelAddIn
Services.AddHttpClient()
.AddSingleton((Application)ExcelDnaUtil.Application)
.AddSingleton<IDatabaseClient, RhDatabaseClient>()
.AddSingleton<IAddInConfiguration, RhAddInConfiguration>()
.AddSingleton<IDatabaseClient, RhDatabaseClient>()
.AddTransient<IFileDialog, ExcelFileDialog>()
.AddTransient<IExcelReader, RhExcelReader>()
.AddTransient<IExcelWriter, RhExcelWriter>();
.AddTransient<IExcelReader, RhExcelReader>();
Services.AddSingleton<WriterFactory>();
Services.AddTransient<RhExcelWriter>()
.AddTransient<IExcelWriter, RhExcelWriter>(s => s.GetService<RhExcelWriter>());
Services.AddTransient<RhDxfWriter>()
.AddTransient<IExcelWriter, RhDxfWriter>(s => s.GetService<RhDxfWriter>());
Services.AddSingleton<ToolFactory>();
ServiceProvider = Services.BuildServiceProvider();
Configuration = ServiceProvider.GetService<IAddInConfiguration>();

View File

@ -14,7 +14,7 @@ public class RhSolutionsFunction
{
IDatabaseClient databaseClient = RhSolutionsAddIn.ServiceProvider.GetService<IDatabaseClient>();
Sku.TryParse(line, out var skus);
ProductSku.TryParse(line, out var skus);
if (ExcelAsyncUtil.Run("Database request", line, delegate
{

View File

@ -27,6 +27,7 @@ public class RibbonController : ExcelRibbon
<button id='export' getEnabled='GetExportEnabled' label='Экспорт в новый файл' size='normal' imageMso='PivotExportToExcel' onAction='OnToolPressed'/>
<button id='convert' getEnabled='GetConvertEnabled' label='Актуализировать' size='normal' imageMso='FileUpdate' onAction='OnToolPressed'/>
<button id='merge' label='Объединить' size='normal' imageMso='Copy' onAction='OnToolPressed'/>
<button id='dxfexport' getEnabled='GetDxfEnabled' label='Экспортировать в DXF' size='normal' imageMso='ExportExcel' onAction='OnToolPressed'/>
</group>
<group id='rausettings' getLabel='GetVersionLabel'>
<button id='setPriceList' getLabel='GetPriceListPathLabel' size='large' imageMso='TableExcelSpreadsheetInsert' onAction='OnSetPricePressed'/>
@ -63,13 +64,8 @@ public class RibbonController : ExcelRibbon
{
try
{
using ToolBase tool = control.Id switch
{
"export" => new ExportTool(),
"convert" => new ConvertTool(),
"merge" => new MergeTool(),
_ => throw new Exception("Неизвестный инструмент"),
};
var toolFactory = RhSolutionsAddIn.ServiceProvider.GetService<ToolFactory>();
using Tool tool = toolFactory.GetTool(control.Id);
tool.Execute();
}
@ -108,6 +104,18 @@ public class RibbonController : ExcelRibbon
}
}
public bool GetDxfEnabled(IRibbonControl control)
{
if (RhSolutionsAddIn.Excel.ActiveWorkbook == null)
return false;
else
{
Worksheet worksheet = RhSolutionsAddIn.Excel.ActiveWorkbook.ActiveSheet;
return worksheet.IsValidSource();
}
}
public string GetVersionLabel(IRibbonControl control)
{
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

View File

@ -1,35 +0,0 @@
using System.Linq;
namespace RhSolutions.Models
{
public class Product
{
public string ProductLine { get; set; }
public string ProductSku { get; set; }
public string Name { get; set; }
public override bool Equals(object obj)
{
if (obj as Product == null)
return false;
Product other = obj as Product;
return ProductLine == other.ProductLine &&
ProductSku == other.ProductSku &&
Name == other.Name;
}
public override int GetHashCode()
{
string[] properties = new[]
{
ProductLine,
ProductSku,
Name
};
return string.Concat(properties.Where(p => p != null)).GetHashCode();
}
}
}

View File

@ -11,6 +11,7 @@
<Reference Path="Microsoft.Extensions.Options.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.Primitives.dll" Pack="true" />
<Reference Path="Newtonsoft.Json.dll" Pack="true" />
<Reference Path="netDxf.dll" Pack="true" />
<Reference Path="RhSolutions.Sku.dll" Pack="true" />
<Reference Path="System.Buffers.dll" Pack="true" />
<Reference Path="System.Diagnostics.DiagnosticSource.dll" Pack="true" />

View File

@ -34,8 +34,9 @@
<PackageReference Include="Microsoft.Bcl.HashCode" Version="1.1.1" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
<PackageReference Include="netDxf" Version="2022.11.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="RhSolutions.Sku" Version="0.1.1" />
<PackageReference Include="RhSolutions.Sku" Version="0.1.5" />
<PackageReference Include="System.Buffers" Version="4.5.1" />
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.4" />
</ItemGroup>

View File

@ -15,7 +15,8 @@ public class RhAddInConfiguration : ApplicationSettingsBase, IAddInConfiguration
["OldSku"] = OldSkuHeader,
["Sku"] = SkuHeader,
["ProductLine"] = ProductLineHeader,
["Name"] = NameHeader
["Name"] = NameHeader,
["Measure"] = MeasureHeader
};
}
@ -70,6 +71,16 @@ public class RhAddInConfiguration : ApplicationSettingsBase, IAddInConfiguration
}
}
[UserScopedSetting]
[DefaultSettingValue("Ед. изм.")]
public string MeasureHeader
{
get
{
return (string)this[nameof(MeasureHeader)];
}
}
[UserScopedSetting]
public string PriceListPath
{

View File

@ -19,7 +19,7 @@ public class RhDatabaseClient : IDatabaseClient
{
string request;
if (Sku.TryParse(line, out var skus))
if (ProductSku.TryParse(line, out var skus))
{
request = @"https://rh.cebotari.ru/api/products/" + skus.FirstOrDefault().ToString();
}

View File

@ -0,0 +1,482 @@
using netDxf;
using netDxf.Blocks;
using netDxf.Entities;
using netDxf.Header;
using System.Diagnostics;
using System.IO;
using Line = netDxf.Entities.Line;
namespace RhSolutions.Services;
public class RhDxfWriter : IExcelWriter
{
private readonly string file;
private readonly DxfDocument doc;
private Dictionary<Product, double> productDict;
private readonly Block tableBlock;
public RhDxfWriter()
{
string filepath = RhSolutionsAddIn.Excel.ActiveWorkbook.Path;
string filename = Path.GetFileNameWithoutExtension(RhSolutionsAddIn.Excel.ActiveWorkbook.Name);
file = Path.Combine(filepath, $"{filename}.dxf");
doc = new DxfDocument();
tableBlock = CreateTable();
}
public void WriteProducts(Dictionary<Product, double> products)
{
WriteProducts(new[] { (string.Empty, products) });
}
public void WriteProducts(IEnumerable<(string, Dictionary<Product, double>)> products)
{
productDict = products.First().Item2;
doc.Layers.Add(new netDxf.Tables.Layer("Таблицы"));
int tablesCount = productDict.Count / 27 + (productDict.Count % 27 == 0 ? 0 : 1);
int tablePosition = 0;
for (int i = 0; i < tablesCount; i++)
{
var insertion = new Insert(tableBlock, new Vector2(tablePosition, 0))
{
Layer = doc.Layers["Таблицы"]
};
var pArray = products.First().Item2.Select(p => p.Key).ToArray();
for (int row = 0; row < 27 && i * 27 + row < pArray.Length; row++)
{
insertion.Attributes.AttributeWithTag($"Name{row}").Value = pArray[i * 27 + row].Name.Replace("\n", " ");
insertion.Attributes.AttributeWithTag($"ProductSku{row}").Value = pArray[i * 27 + row].ProductSku;
insertion.Attributes.AttributeWithTag($"Rh{row}").Value = "«РЕХАУ»";
insertion.Attributes.AttributeWithTag($"Amount{row}").Value = productDict[pArray[i * 27 + row]].ToString();
string measure = string.Empty;
switch (pArray[i * 27 + row].ProductMeasure)
{
case Measure.Kg:
measure = "кг";
break;
case Measure.M:
measure = "м";
break;
case Measure.M2:
measure = "м2";
break;
case Measure.P:
measure = "шт";
break;
default:
break;
}
insertion.Attributes.AttributeWithTag($"Measure{row}").Value = measure;
}
insertion.Attributes.AttributeWithTag("Sheet").Value = (i + 1).ToString();
tablePosition += 43000;
doc.Entities.Add(insertion);
}
doc.Save(file);
DxfVersion dxfVersion = DxfDocument.CheckDxfFileVersion(file);
if (dxfVersion < DxfVersion.AutoCad2000)
return;
}
private Block CreateTable()
{
List<EntityObject> entities = new();
entities.AddRange(new[]
{
new Line(new Vector2(0, 29700), new Vector2(0, 0)),
new Line(new Vector2(0, 0), new Vector2(42000, 0)),
new Line(new Vector2(42000, 0), new Vector2(42000, 29700)),
new Line(new Vector2(42000, 29700), new Vector2(0, 29700)),
});
entities.AddRange(new[]
{
new Line(new Vector2(2000, 29200), new Vector2(2000, 500))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(2000, 500), new Vector2(41500, 500))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(41500, 500), new Vector2(41500, 29200))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(41500, 29200), new Vector2(2000, 29200))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(800, 9000), new Vector2(2000, 9000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(2000, 6500), new Vector2(800, 6500))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(2000, 3000), new Vector2(800, 3000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(2000, 500), new Vector2(800, 500))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(800, 500), new Vector2(800, 9000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(1300, 500), new Vector2(1300, 9000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(23000,2000), new Vector2(41500, 2000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(23000, 1500), new Vector2(29500, 1500))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(23000, 1000), new Vector2(29500, 1000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(23000, 500), new Vector2(23000, 2000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(24000, 500), new Vector2(24000, 2000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(25000, 500), new Vector2(25000, 2000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(26000, 500), new Vector2(26000, 2000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(27000, 500), new Vector2(27000, 2000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(28500, 500), new Vector2(28500, 2000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(29500, 500), new Vector2(29500, 2000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(40500, 500), new Vector2(40500, 2000))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(40500, 1300), new Vector2(41500, 1300))
{
Lineweight = Lineweight.W30
},
});
entities.AddRange(new[]
{
new Line(new Vector2(4000, 29200), new Vector2(4000, 4200))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(17000, 29200), new Vector2(17000, 4200))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(23000, 29200), new Vector2(23000, 4200))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(26500, 29200), new Vector2(26500, 4200))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(31000, 29200), new Vector2(31000, 4200))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(33000, 29200), new Vector2(33000, 4200))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(35000, 29200), new Vector2(35000, 4200))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(37500, 29200), new Vector2(37500, 4200))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(4000, 29200), new Vector2(4000, 4200))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(41500, 26500), new Vector2(2000, 26500))
{
Lineweight = Lineweight.W30
},
new Line(new Vector2(41500, 25700), new Vector2(2000, 25700))
{
Lineweight = Lineweight.W30
}
});
int y = 4200;
for (int i = 0; i < 27; i++)
{
var line = new Line(new Vector2(41500, y), new Vector2(2000, y));
entities.Add(line);
y += 800;
}
entities.AddRange(new[]
{
new Text("Инв.N подл.", new Vector2(1150, 700), 250)
{
Rotation = 90,
WidthFactor = 0.85
},
new Text("Подпись и дата", new Vector2(1150, 3130), 250)
{
Rotation = 90,
WidthFactor = 0.85
},
new Text("Взам.инв.N", new Vector2(1150, 6580), 250)
{
Rotation = 90,
WidthFactor = 0.85
},
new Text("Позиция", new Vector2(3000, 27850), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("1", new Vector2(3000, 26200), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("Наименование и техническая характеристика", new Vector2(10500, 27850), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("2", new Vector2(10500, 26200), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("Тип, марка оборудования.", new Vector2(20000, 28250), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("Обозначение документа,", new Vector2(20000, 27850), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("опросного листа", new Vector2(20000, 27450), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("3", new Vector2(20000, 26200), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("Код оборудования,", new Vector2(24750, 28250), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("изделия,", new Vector2(24750, 27850), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("материала", new Vector2(24750, 27450), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("4", new Vector2(24750, 26200), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("Завод-изготовитель", new Vector2(28750, 27850), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("5", new Vector2(28750, 26200), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("Единица", new Vector2(32000, 27850), 250)
{
Alignment = TextAlignment.BottomCenter,
WidthFactor = 0.85
},
new Text("измерения", new Vector2(32000, 27850), 250)
{
Alignment = TextAlignment.TopCenter,
WidthFactor = 0.85
},
new Text("6", new Vector2(32000, 26200), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("Коли-", new Vector2(34000, 27850), 250)
{
Alignment = TextAlignment.BottomCenter,
WidthFactor = 0.85
},
new Text("чество", new Vector2(34000, 27850), 250)
{
Alignment = TextAlignment.TopCenter,
WidthFactor = 0.85
},
new Text("7", new Vector2(34000, 26200), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("Масса,", new Vector2(36250, 28250), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("единицы,", new Vector2(36250, 27850), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("кг", new Vector2(36250, 27450), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("8", new Vector2(36250, 26200), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("Примечания", new Vector2(39500, 27850), 250)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85
},
new Text("Изм.", new Vector2(23100, 525), 300)
{
Alignment = TextAlignment.BottomLeft,
WidthFactor = 0.65
},
new Text("Кол.уч", new Vector2(24100, 525), 300)
{
Alignment = TextAlignment.BottomLeft,
WidthFactor = 0.65
},
new Text("Лист", new Vector2(25100, 525), 300)
{
Alignment = TextAlignment.BottomLeft,
WidthFactor = 0.65
},
new Text("Nдок.", new Vector2(26100, 525), 300)
{
Alignment = TextAlignment.BottomLeft,
WidthFactor = 0.65
},
new Text("Подп.", new Vector2(27100, 525), 300)
{
Alignment = TextAlignment.BottomLeft,
WidthFactor = 0.65
},
new Text("Дата", new Vector2(28600, 525), 300)
{
Alignment = TextAlignment.BottomLeft,
WidthFactor = 0.65
},
new Text("Лист", new Vector2(41000, 1650), 300)
{
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.65
}
});
Block block = new("Таблица спецификации", entities);
y = 25400;
for (int i = 0; i < 27; i++)
{
block.AttributeDefinitions.Add(new AttributeDefinition($"Name{i}")
{
Position = new Vector3(4180, y, 0),
Alignment = TextAlignment.MiddleLeft,
WidthFactor = 0.85,
Height = 250
});
block.AttributeDefinitions.Add(new AttributeDefinition($"ProductSku{i}")
{
Position = new Vector3(24750, y, 0),
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85,
Height = 250
});
block.AttributeDefinitions.Add(new AttributeDefinition($"Rh{i}")
{
Position = new Vector3(28750, y, 0),
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85,
Height = 250
});
block.AttributeDefinitions.Add(new AttributeDefinition($"Measure{i}")
{
Position = new Vector3(32000, y, 0),
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85,
Height = 250
});
block.AttributeDefinitions.Add(new AttributeDefinition($"Amount{i}")
{
Position = new Vector3(34000, y, 0),
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.85,
Height = 250
});
y -= 800;
}
block.AttributeDefinitions.Add(new AttributeDefinition($"Sheet")
{
Position = new Vector3(41000, 950, 0),
Alignment = TextAlignment.MiddleCenter,
WidthFactor = 0.65,
Height = 300
});
return block;
}
public void Dispose()
{
Process.Start(file);
}
}

View File

@ -38,7 +38,7 @@ public class RhExcelReader : IExcelReader, IDisposable
{
object currentCell = cells[row, column];
if (Sku.TryParse(currentCell.ToString(), out var validSku))
if (ProductSku.TryParse(currentCell.ToString(), out var validSku))
{
currentSku = validSku.FirstOrDefault().ToString() ?? null;
}
@ -92,8 +92,9 @@ public class RhExcelReader : IExcelReader, IDisposable
Range AmountCell = worksheet.Cells.Find(headers["Amount"]),
SkuCell = worksheet.Cells.Find(headers["Sku"]),
ProductLineCelll = worksheet.Cells.Find(headers["ProductLine"]),
NameCell = worksheet.Cells.Find(headers["Name"]);
ProductLineCell = worksheet.Cells.Find(headers["ProductLine"]),
NameCell = worksheet.Cells.Find(headers["Name"]),
MeasureCell = worksheet.Cells.Find(headers["Measure"]);
var lastRowIndex = worksheet.Cells[worksheet.Rows.Count, AmountCell.Column]
.End[XlDirection.xlUp].Row;
@ -105,21 +106,43 @@ public class RhExcelReader : IExcelReader, IDisposable
if (amount != null && amount.Value != 0)
{
object programLine = worksheet.Cells[row, ProductLineCelll.Column].Value2;
object productLine = worksheet.Cells[row, ProductLineCell.Column].Value2;
object name = worksheet.Cells[row, NameCell.Column].Value2;
object sku = worksheet.Cells[row, SkuCell.Column].Value2;
object measure = worksheet.Cells[row, MeasureCell.Column].Value2;
Measure productMeasure;
if (programLine == null || name == null || sku == null)
switch (measure.ToString())
{
case "м":
productMeasure = Measure.M;
break;
case "шт":
productMeasure = Measure.P;
break;
case "м2":
productMeasure = Measure.M2;
break;
case "кг":
productMeasure = Measure.Kg;
break;
default:
productMeasure = Measure.P;
break;
}
if (productLine == null || name == null || sku == null)
continue;
if (!Sku.TryParse(sku.ToString(), out _))
if (!ProductSku.TryParse(sku.ToString(), out _))
continue;
Product p = new()
{
ProductSku = sku.ToString(),
ProductLine = programLine.ToString(),
Name = name.ToString()
ProductLine = productLine.ToString(),
Name = name.ToString(),
ProductMeasure = productMeasure
};
if (readResult.ContainsKey(p))

View File

@ -0,0 +1,24 @@
namespace RhSolutions.Services;
public class WriterFactory
{
private readonly IServiceProvider _serviceProvider;
public WriterFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IExcelWriter GetWriter(string writerName)
{
if (writerName.Equals("Dxf"))
{
return (IExcelWriter)_serviceProvider.GetService(typeof(RhDxfWriter));
}
else
{
return (IExcelWriter)_serviceProvider.GetService(typeof(RhExcelWriter));
}
}
}

View File

@ -8,13 +8,18 @@ namespace RhSolutions.Tools;
#if !NET472
[SupportedOSPlatform("windows")]
#endif
internal class ConvertTool : ToolBase
internal class ConvertTool : Tool
{
public ConvertTool(IServiceProvider provider) : base(provider)
{
}
public override void Execute()
{
Application app = RhSolutionsAddIn.Excel.Application;
Worksheet worksheet = app.ActiveWorkbook.ActiveSheet;
var products = _reader.ReadProducts(new[] { worksheet });
_writer = _writerFactory.GetWriter("Excel");
_writer.WriteProducts(products);
}
}

View File

@ -0,0 +1,24 @@
#if !NET472
using System.Runtime.Versioning;
#endif
namespace RhSolutions.Tools;
#if !NET472
[SupportedOSPlatform("windows")]
#endif
internal class DxfTool : Tool
{
public DxfTool(IServiceProvider provider) : base(provider)
{
}
public override void Execute()
{
Application app = RhSolutionsAddIn.Excel.Application;
Worksheet worksheet = app.ActiveWorkbook.ActiveSheet;
var products = _reader.ReadProducts(new[] { worksheet });
_writer = _writerFactory.GetWriter("Dxf");
_writer.WriteProducts(products);
}
}

View File

@ -17,7 +17,9 @@ namespace RhSolutions.Tools
{
RhSolutionsAddIn.Excel.SheetSelectionChange += RefreshExportButton;
RhSolutionsAddIn.Excel.SheetActivate += RefreshConvertButton;
RhSolutionsAddIn.Excel.SheetActivate += RefreshDxfButton;
RhSolutionsAddIn.Excel.WorkbookActivate += RefreshConvertButton;
RhSolutionsAddIn.Excel.WorkbookActivate += RefreshDxfButton;
RhSolutionsAddIn.Configuration.OnSettingsChange += RefreshSettingTitle;
}
@ -25,7 +27,9 @@ namespace RhSolutions.Tools
{
RhSolutionsAddIn.Excel.SheetSelectionChange -= RefreshExportButton;
RhSolutionsAddIn.Excel.SheetActivate -= RefreshConvertButton;
RhSolutionsAddIn.Excel.SheetActivate -= RefreshDxfButton;
RhSolutionsAddIn.Excel.WorkbookActivate -= RefreshConvertButton;
RhSolutionsAddIn.Excel.WorkbookActivate -= RefreshDxfButton;
RhSolutionsAddIn.Configuration.OnSettingsChange -= RefreshSettingTitle;
}
@ -34,6 +38,11 @@ namespace RhSolutions.Tools
RibbonController.RefreshControl("convert");
}
private static void RefreshDxfButton(object sh)
{
RibbonController.RefreshControl("dxfexport");
}
private static void RefreshExportButton(object sh, Range target)
{
RibbonController.RefreshControl("export");

View File

@ -8,12 +8,17 @@ namespace RhSolutions.Tools;
#if !NET472
[SupportedOSPlatform("windows")]
#endif
internal class ExportTool : ToolBase
internal class ExportTool : Tool
{
public ExportTool(IServiceProvider provider) : base(provider)
{
}
public override void Execute()
{
Application app = RhSolutionsAddIn.Excel.Application;
var products = _reader.ReadProducts(app.Selection);
_writer = _writerFactory.GetWriter("Excel");
_writer.WriteProducts(products);
}
}

View File

@ -1,23 +1,24 @@
#if !NET472
using System.Runtime.Versioning;
using RhSolutions;
using RhSolutions.Models;
using RhSolutions.Tools;
#endif
namespace RhSolutions.Tools;
#if !NET472
[SupportedOSPlatform("windows")]
#endif
internal class MergeTool : ToolBase
internal class MergeTool : Tool
{
public MergeTool(IServiceProvider provider) : base(provider)
{
}
public override void Execute()
{
IFileDialog dialog = RhSolutionsAddIn.ServiceProvider.GetRequiredService<IFileDialog>();
string[] files = dialog.GetFiles();
var products = _reader.ReadProducts(files);
_writer = _writerFactory.GetWriter("Excel");
_writer.WriteProducts(products);
}
}

View File

@ -7,15 +7,16 @@ namespace RhSolutions.Tools;
#if !NET472
[SupportedOSPlatform("windows")]
#endif
internal abstract class ToolBase : IDisposable
internal abstract class Tool : IDisposable
{
protected readonly IExcelReader _reader;
protected readonly IExcelWriter _writer;
protected readonly WriterFactory _writerFactory;
protected IExcelWriter _writer;
public ToolBase()
public Tool(IServiceProvider provider)
{
_reader = RhSolutionsAddIn.ServiceProvider.GetRequiredService<IExcelReader>();
_writer = RhSolutionsAddIn.ServiceProvider.GetRequiredService<IExcelWriter>();
_reader = provider.GetRequiredService<IExcelReader>();
_writerFactory = provider.GetRequiredService<WriterFactory>();
}
public void Dispose()

View File

@ -0,0 +1,17 @@
namespace RhSolutions.Tools;
internal class ToolFactory
{
public Tool GetTool(string toolName)
{
Tool tool = toolName switch
{
"export" => new ExportTool(RhSolutionsAddIn.ServiceProvider),
"convert" => new ConvertTool(RhSolutionsAddIn.ServiceProvider),
"merge" => new MergeTool(RhSolutionsAddIn.ServiceProvider),
"dxfexport" => new DxfTool(RhSolutionsAddIn.ServiceProvider),
_ => throw new Exception("Неизвестный инструмент"),
};
return tool;
}
}

View File

@ -1,26 +0,0 @@
namespace RhSolutions.ExcelExtensions;
public sealed class Cell
{
public Table ParentTable { get; }
public Row ParentRow
{
get => ParentTable.Rows[ParentTable.Range.Row - _range.Row];
}
public Column ParentColumn
{
get => ParentTable.Columns[ParentTable.Range.Column - _range.Column];
}
public object Value
{
get => _range.Cells[1, 1].Value2;
set => _range.Cells[1, 1].Value2 = value;
}
private Range _range;
public Cell(Range range, Table table)
{
_range = range;
ParentTable = table;
}
}

View File

@ -1,65 +0,0 @@
namespace RhSolutions.ExcelExtensions;
public sealed class Column
{
public Table ParentTable { get; }
public string Header
{
get => _range.Cells[1, 1].Value2.ToString() ?? String.Empty;
}
public int Index
{
get => _range.Column - ParentTable.Range.Column;
}
public int Length
{
get => _range.Rows.Count;
}
private Cell[] _cells;
private readonly Range _range;
public Column(Range range, Table table)
{
_cells = new Cell[range.Rows.Count];
_range = range;
ParentTable = table ??
throw new ArgumentNullException("table");
}
public Cell this[int index]
{
get
{
if (_cells[index] == null)
{
_cells[index] = new Cell(_range.Cells[index + 1, 1], ParentTable);
return _cells[index];
}
else
{
return _cells[index];
}
}
set
{
if (_cells[index] == null)
{
_cells[index] = new Cell(_range.Cells[index + 1, 1], ParentTable);
_cells[index].Value = value;
}
else
{
_cells[index].Value = value;
}
}
}
public Column AddLeft()
{
_range.EntireColumn
.Insert(XlInsertShiftDirection.xlShiftToRight,
XlInsertFormatOrigin.xlFormatFromRightOrBelow);
return ParentTable.Columns[this.Index - 1];
}
}

View File

@ -1,49 +0,0 @@
using System.Collections;
namespace RhSolutions.ExcelExtensions;
public class Columns : IEnumerable<Column>
{
public Table ParentTable { get; }
public int Length
{
get => _range.Columns.Count;
}
private Column[] _columns;
private Range _range;
public Columns(Table parentTable)
{
ParentTable = parentTable;
_range = parentTable.Range;
_columns = new Column[Length];
}
public Column this[int index]
{
get
{
if (index < 0 || index >= Length)
{
throw new IndexOutOfRangeException();
}
if (_columns[index] == null)
{
_columns[index] = new Column(_range.Columns[index + 1], ParentTable);
return _columns[index];
}
else
{
return _columns[index];
}
}
}
public IEnumerator<Column> GetEnumerator()
{
return new ColumnsEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

View File

@ -1,52 +0,0 @@
using System.Collections;
namespace RhSolutions.ExcelExtensions;
public class ColumnsEnumerator: IEnumerator<Column>
{
private Columns _columns;
private int position = -1;
object IEnumerator.Current
{
get
{
return Current;
}
}
public Column Current
{
get
{
try
{
return _columns[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
public ColumnsEnumerator(Columns columns)
{
_columns = columns;
}
public bool MoveNext()
{
position++;
return (position < _columns.Length);
}
public void Reset()
{
position = -1;
}
public void Dispose()
{
}
}

View File

@ -1,15 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net472;net6.0-windows7.0</TargetFrameworks>
<LangVersion>10</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ExcelDna.Interop" Version="15.0.1" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
</ItemGroup>
</Project>

View File

@ -1,54 +0,0 @@
namespace RhSolutions.ExcelExtensions;
public sealed class Row
{
public Table ParentTable { get; }
public int Index
{
get => _range.Row - ParentTable.Range.Row;
}
public int Length
{
get => _range.Columns.Count;
}
private readonly Cell[] _cells;
private readonly Range _range;
public Row(Range range, Table table)
{
_cells = new Cell[range.Columns.Count];
_range = range;
ParentTable = table ??
throw new ArgumentNullException("table");
}
public Cell this[int index]
{
get
{
if (index < 0 || index >= Length)
{
throw new IndexOutOfRangeException();
}
if (_cells[index] == null)
{
_cells[index] = new Cell(_range.Cells[1, index + 1], ParentTable);
return _cells[index];
}
else
{
return _cells[index];
}
}
}
public Cell this[string header]
{
get
{
int columnIndex = ParentTable.ColumnByHeader(header).Index;
return this[columnIndex];
}
}
}

View File

@ -1,44 +0,0 @@
using System.Collections;
namespace RhSolutions.ExcelExtensions;
public class Rows : IEnumerable<Row>
{
public Table ParentTable { get; }
public int Length
{
get => _range.Rows.Count;
}
private Row[] _rows;
private Range _range;
public Rows(Table parentTable)
{
ParentTable = parentTable;
_range = parentTable.Range;
_rows = new Row[Length];
}
public Row this[int index]
{
get
{
if (_rows[index] == null)
{
_rows[index] = new Row(_range.Rows[index + 1], ParentTable);
return _rows[index];
}
else
{
return _rows[index];
}
}
}
public IEnumerator<Row> GetEnumerator()
{
return new RowsEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

View File

@ -1,52 +0,0 @@
using System.Collections;
namespace RhSolutions.ExcelExtensions;
public class RowsEnumerator : IEnumerator<Row>
{
private Rows _rows;
private int position = -1;
object IEnumerator.Current
{
get
{
return Current;
}
}
public Row Current
{
get
{
try
{
return _rows[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
public RowsEnumerator(Rows rows)
{
_rows = rows;
}
public bool MoveNext()
{
position++;
return (position < _rows.Length);
}
public void Reset()
{
position = -1;
}
public void Dispose()
{
}
}

View File

@ -1,64 +0,0 @@
namespace RhSolutions.ExcelExtensions;
public class Table
{
public Range Range { get; protected set; }
public Table ParentTable { get; protected set; }
public Rows Rows { get; }
public Columns Columns { get; }
private Dictionary<string, Column> _columnsByHeader;
public Table(Range range)
{
Range = range;
ParentTable = this;
Rows = new Rows(this);
Columns = new Columns(this);
_columnsByHeader = new();
foreach(var column in Columns)
{
if (_columnsByHeader.ContainsKey(column.Header))
{
throw new ArgumentException($"Заголовок столбца {column.Header} не уникален");
}
else
{
_columnsByHeader.Add(column.Header, column);
}
}
}
public Column ColumnByHeader(string header)
{
return _columnsByHeader[header];
}
public Cell this[int row, int column]
{
get => this.Rows[row][column];
}
public IEnumerable<Cell> Search(object item)
{
Range firstFound = Range.Find(item);
if (firstFound == null)
{
yield break;
}
Range nextFound = firstFound;
while (true)
{
yield return this[nextFound.Row - ParentTable.Range.Row, nextFound.Column - ParentTable.Range.Column];
nextFound = Range.FindNext(nextFound);
if (nextFound.Row == firstFound.Row
&& nextFound.Column == firstFound.Column)
{
yield break;
}
}
}
}

View File

@ -1,3 +0,0 @@
global using Microsoft.Office.Interop.Excel;
global using System.Collections.Generic;
global using Range = Microsoft.Office.Interop.Excel.Range;