Compare commits

...

10 Commits

23 changed files with 385 additions and 242 deletions

View File

@ -40,6 +40,8 @@ public sealed class RhSolutionsAddIn : IExcelAddIn
Services.AddTransient<SleevesCalculator>() Services.AddTransient<SleevesCalculator>()
.AddTransient<IFittingsCalculator, SleevesCalculator>(s => s.GetService<SleevesCalculator>()); .AddTransient<IFittingsCalculator, SleevesCalculator>(s => s.GetService<SleevesCalculator>());
Services.AddTransient<IOcrClient, YandexOcrClient>();
Services.AddSingleton<ToolFactory>(); Services.AddSingleton<ToolFactory>();
ServiceProvider = Services.BuildServiceProvider(); ServiceProvider = Services.BuildServiceProvider();

View File

@ -33,7 +33,7 @@ public class RibbonController : ExcelRibbon
<button id='dxfexport' getEnabled='GetDxfEnabled' label='DXF' size='large' image='DXF' onAction='OnToolPressed'/> <button id='dxfexport' getEnabled='GetDxfEnabled' label='DXF' size='large' image='DXF' onAction='OnToolPressed'/>
</group> </group>
<group id='importTab' label='OCR'> <group id='importTab' label='OCR'>
<button id='ocr' label='Распознать таблицу' size='large' imageMso='TableInsert' onAction='OnToolPressed'/> <button id='ocr' getEnabled='GetOcrEnabled' label='Распознать таблицу' size='large' imageMso='TableInsert' onAction='OnToolPressed'/>
</group> </group>
<group id='settings' getLabel='GetVersionLabel'> <group id='settings' getLabel='GetVersionLabel'>
<button id='setPriceList' getLabel='GetPriceListPathLabel' size='large' image='RhSolutions' onAction='OnSetPricePressed'/> <button id='setPriceList' getLabel='GetPriceListPathLabel' size='large' image='RhSolutions' onAction='OnSetPricePressed'/>
@ -71,7 +71,7 @@ public class RibbonController : ExcelRibbon
try try
{ {
var toolFactory = RhSolutionsAddIn.ServiceProvider.GetService<ToolFactory>(); var toolFactory = RhSolutionsAddIn.ServiceProvider.GetService<ToolFactory>();
using Tool tool = toolFactory.GetTool(control.Id); using ITool tool = toolFactory.GetTool(control.Id);
tool.Execute(); tool.Execute();
} }
@ -103,6 +103,13 @@ public class RibbonController : ExcelRibbon
} }
} }
public bool GetOcrEnabled(IRibbonControl control)
{
return RhSolutionsAddIn.Excel.ActiveWorkbook != null &&
!string.IsNullOrEmpty(RhSolutionsAddIn.Configuration["x-folder-id"]) &&
!string.IsNullOrEmpty(RhSolutionsAddIn.Configuration["apiKey"]);
}
public string GetVersionLabel(IRibbonControl control) public string GetVersionLabel(IRibbonControl control)
{ {
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

View File

@ -0,0 +1,28 @@
namespace RhSolutions.Models;
public class OcrResponse
{
public Result Result { get; set; }
}
public class Result
{
public TextAnnotation TextAnnotation { get; set; }
}
public class TextAnnotation
{
public List<Table> Tables { get; set; }
}
public class Table
{
public string RowCount { get; set; }
public string ColumnCount { get; set; }
public List<Cell> Cells { get; set; }
}
public class Cell
{
public string RowIndex { get; set; }
public string ColumnIndex { get; set; }
public string Text { get; set; }
}

View File

@ -1,5 +1,6 @@
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Microsoft.Extensions.Configuration.UserSecrets;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
@ -33,3 +34,4 @@ using System.Runtime.InteropServices;
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.9.5.1")] [assembly: AssemblyVersion("1.9.5.1")]
[assembly: AssemblyFileVersion("1.9.5.1")] [assembly: AssemblyFileVersion("1.9.5.1")]
[assembly: UserSecretsId("d4bb704e-14a5-421f-8f2d-0ffb66d090a2")]

View File

@ -6,8 +6,16 @@
<Reference Path="Microsoft.Bcl.HashCode.dll" Pack="true" /> <Reference Path="Microsoft.Bcl.HashCode.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.Caching.Abstractions.dll" Pack="true" /> <Reference Path="Microsoft.Extensions.Caching.Abstractions.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.Caching.Memory.dll" Pack="true" /> <Reference Path="Microsoft.Extensions.Caching.Memory.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.Configuration.Abstractions.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.Configuration.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.Configuration.FileExtensions.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.Configuration.Json.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.Configuration.UserSecrets.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.DependencyInjection.Abstractions.dll" Pack="true" /> <Reference Path="Microsoft.Extensions.DependencyInjection.Abstractions.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.DependencyInjection.dll" Pack="true" /> <Reference Path="Microsoft.Extensions.DependencyInjection.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.FileProviders.Abstractions.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.FileProviders.Physical.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.FileSystemGlobbing.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.Http.dll" Pack="true" /> <Reference Path="Microsoft.Extensions.Http.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.Logging.Abstractions.dll" Pack="true" /> <Reference Path="Microsoft.Extensions.Logging.Abstractions.dll" Pack="true" />
<Reference Path="Microsoft.Extensions.Logging.dll" Pack="true" /> <Reference Path="Microsoft.Extensions.Logging.dll" Pack="true" />
@ -21,6 +29,8 @@
<Reference Path="System.Memory.dll" Pack="true" /> <Reference Path="System.Memory.dll" Pack="true" />
<Reference Path="System.Numerics.Vectors.dll" Pack="true" /> <Reference Path="System.Numerics.Vectors.dll" Pack="true" />
<Reference Path="System.Runtime.CompilerServices.Unsafe.dll" Pack="true" /> <Reference Path="System.Runtime.CompilerServices.Unsafe.dll" Pack="true" />
<Reference Path="System.Text.Encodings.Web.dll" Pack="true" />
<Reference Path="System.Text.Json.dll" Pack="true" />
<Reference Path="System.Threading.Tasks.Extensions.dll" Pack="true" /> <Reference Path="System.Threading.Tasks.Extensions.dll" Pack="true" />
<Reference Path="System.ValueTuple.dll" Pack="true" /> <Reference Path="System.ValueTuple.dll" Pack="true" />
<Reference Path="SnippingTool.dll" Pack="true" /> <Reference Path="SnippingTool.dll" Pack="true" />

View File

@ -2,12 +2,14 @@
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>net472;net6.0-windows</TargetFrameworks> <TargetFrameworks>net472;net6.0-windows</TargetFrameworks>
<LangVersion>10</LangVersion> <LangVersion>10</LangVersion>
<OutputType>Library</OutputType> <ProduceReferenceAssembly>false</ProduceReferenceAssembly>
<RootNamespace>RhSolutions</RootNamespace>
<AssemblyName>RhSolutions.AddIn</AssemblyName>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<EnableDynamicLoading>true</EnableDynamicLoading>
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
<ImportWindowsDesktopTargets>true</ImportWindowsDesktopTargets> <UserSecretsId>d4bb704e-14a5-421f-8f2d-0ffb66d090a2</UserSecretsId>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<NoWarn>CA1416</NoWarn>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="ExcelDna.AddIn" Version="1.8.0" /> <PackageReference Include="ExcelDna.AddIn" Version="1.8.0" />
@ -18,6 +20,9 @@
<PackageReference Include="Microsoft.Bcl.HashCode" Version="1.1.1" /> <PackageReference Include="Microsoft.Bcl.HashCode" Version="1.1.1" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" /> <PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.1" /> <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Physical" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" /> <PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" />
<PackageReference Include="netDxf" Version="2022.11.2" /> <PackageReference Include="netDxf" Version="2022.11.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />

View File

@ -1,21 +1,32 @@
using Microsoft.Win32; using Microsoft.Extensions.Configuration;
using Microsoft.Win32;
using System.IO; using System.IO;
namespace RhSolutions.Services; namespace RhSolutions.Services;
public class AddInConfiguration : IAddInConfiguration public class AddInConfiguration : IAddInConfiguration
{ {
private IConfiguration _configuration;
private RegistryKey _rootKey; private RegistryKey _rootKey;
private string _priceListPath; private string _priceListPath;
private Dictionary<string, string> _priceListHeaders; private Dictionary<string, string> settingsValues;
public string this[string key]
{
get => _configuration[key];
}
public event IAddInConfiguration.SettingsHandler OnSettingsChange; public event IAddInConfiguration.SettingsHandler OnSettingsChange;
public AddInConfiguration() public AddInConfiguration()
{ {
_configuration = new ConfigurationBuilder()
.AddUserSecrets<RhSolutionsAddIn>()
.Build();
_rootKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\RhSolutions\RhSolutions-AddIn"); _rootKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\RhSolutions\RhSolutions-AddIn");
_priceListPath = (string)_rootKey.GetValue("PriceListPath"); _priceListPath = (string)_rootKey.GetValue("PriceListPath");
_priceListHeaders = new() settingsValues = new()
{ {
["Amount"] = "Кол-во", ["Amount"] = "Кол-во",
["OldSku"] = "Прежний материал", ["OldSku"] = "Прежний материал",
@ -27,7 +38,7 @@ public class AddInConfiguration : IAddInConfiguration
} }
public string GetPriceListFileName() => Path.GetFileName(_priceListPath); public string GetPriceListFileName() => Path.GetFileName(_priceListPath);
public Dictionary<string, string> GetPriceListHeaders() => _priceListHeaders; public Dictionary<string, string> GetPriceListHeaders() => settingsValues;
public string GetPriceListPath() => _priceListPath; public string GetPriceListPath() => _priceListPath;
public void SaveSettings() public void SaveSettings()

View File

@ -1,7 +1,10 @@
namespace RhSolutions.Services; using Microsoft.Extensions.Configuration;
namespace RhSolutions.Services;
public interface IAddInConfiguration public interface IAddInConfiguration
{ {
string this[string key] { get; }
public string GetPriceListPath(); public string GetPriceListPath();
public void SetPriceListPath(string value); public void SetPriceListPath(string value);
public string GetPriceListFileName(); public string GetPriceListFileName();

View File

@ -0,0 +1,8 @@
using System.Threading.Tasks;
namespace RhSolutions.Services;
public interface IOcrClient
{
public Task<IEnumerable<object[,]>> ProcessImage(string base64Image);
}

View File

@ -0,0 +1,74 @@
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace RhSolutions.Services;
public class YandexOcrClient : IOcrClient
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
private readonly string _xFolderId;
public YandexOcrClient(HttpClient httpClient, IAddInConfiguration configuration)
{
_httpClient = httpClient;
_httpClient.BaseAddress = new Uri("https://ocr.api.cloud.yandex.net/ocr/v1/");
_apiKey = configuration["apiKey"];
_xFolderId = configuration["x-folder-id"];
}
public async Task<IEnumerable<object[,]>> ProcessImage(string base64Image)
{
using StringContent jsonContent = new(
JsonConvert.SerializeObject(new
{
mimeType = "PNG",
languageCodes = new string[] { "ru", "en" },
model = "table",
content = base64Image
}),
Encoding.UTF8,
"application/json");
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Api-Key", _apiKey);
_httpClient.DefaultRequestHeaders.Add("x-folder-id", _xFolderId);
_httpClient.DefaultRequestHeaders.Add("x-data-logging-enable", "true");
using HttpResponseMessage response = await _httpClient.PostAsync("recognizeText", jsonContent);
response.EnsureSuccessStatusCode();
string jsonResponse = await response.Content.ReadAsStringAsync();
OcrResponse deserialized = JsonConvert.DeserializeObject<OcrResponse>(jsonResponse);
if (deserialized != null)
{
var tables = deserialized?.Result?.TextAnnotation?.Tables ?? Enumerable.Empty<Table>();
if (tables.Any())
{
List<object[,]> result = new();
foreach (var table in tables)
{
if (table.Cells == null || table.Cells.Count == 0)
{
continue;
}
int columnCount = int.Parse(table.ColumnCount);
int rowCount = int.Parse(table.RowCount);
object[,] cells = new object[rowCount, columnCount];
foreach (Cell cell in table.Cells)
{
int rowIndex = int.Parse(cell.RowIndex);
int columnIndex = int.Parse(cell.ColumnIndex);
cells[rowIndex, columnIndex] = double.TryParse(cell.Text, out double v) ?
v : cell.Text ?? string.Empty;
}
result.Add(cells);
}
return result;
}
}
return Enumerable.Empty<object[,]>();
}
}

View File

@ -1,20 +1,8 @@
using RhSolutions.AddIn; namespace RhSolutions.Tools;
#if !NET472
using System.Runtime.Versioning;
#endif
namespace RhSolutions.Tools; internal class ConvertTool : ReaderWriterTool, ITool
#if !NET472
[SupportedOSPlatform("windows")]
#endif
internal class ConvertTool : Tool
{ {
public ConvertTool(ReaderFactory readerFactory, WriterFactory writerFactory) : base(readerFactory, writerFactory) public void Execute()
{
}
public override void Execute()
{ {
Application app = RhSolutionsAddIn.Excel.Application; Application app = RhSolutionsAddIn.Excel.Application;
Worksheet worksheet = app.ActiveWorkbook.ActiveSheet; Worksheet worksheet = app.ActiveWorkbook.ActiveSheet;

View File

@ -1,19 +1,8 @@
#if !NET472 namespace RhSolutions.Tools;
using System.Runtime.Versioning;
#endif
namespace RhSolutions.Tools; internal class DxfTool : ReaderWriterTool, ITool
#if !NET472
[SupportedOSPlatform("windows")]
#endif
internal class DxfTool : Tool
{ {
public DxfTool(ReaderFactory readerFactory, WriterFactory writerFactory) : base(readerFactory, writerFactory) public void Execute()
{
}
public override void Execute()
{ {
Application app = RhSolutionsAddIn.Excel.Application; Application app = RhSolutionsAddIn.Excel.Application;
Worksheet worksheet = app.ActiveWorkbook.ActiveSheet; Worksheet worksheet = app.ActiveWorkbook.ActiveSheet;

View File

@ -10,6 +10,7 @@ internal static class EventsUtil
RhSolutionsAddIn.Excel.SheetSelectionChange += RefreshExportButton; RhSolutionsAddIn.Excel.SheetSelectionChange += RefreshExportButton;
RhSolutionsAddIn.Excel.SheetActivate += RefreshButtons; RhSolutionsAddIn.Excel.SheetActivate += RefreshButtons;
RhSolutionsAddIn.Excel.WorkbookActivate += RefreshButtons; RhSolutionsAddIn.Excel.WorkbookActivate += RefreshButtons;
RhSolutionsAddIn.Excel.WorkbookDeactivate += RefreshButtons;
RhSolutionsAddIn.Configuration.OnSettingsChange += RefreshSettingTitle; RhSolutionsAddIn.Configuration.OnSettingsChange += RefreshSettingTitle;
} }
@ -18,6 +19,7 @@ internal static class EventsUtil
RhSolutionsAddIn.Excel.SheetSelectionChange -= RefreshExportButton; RhSolutionsAddIn.Excel.SheetSelectionChange -= RefreshExportButton;
RhSolutionsAddIn.Excel.SheetActivate -= RefreshButtons; RhSolutionsAddIn.Excel.SheetActivate -= RefreshButtons;
RhSolutionsAddIn.Excel.WorkbookActivate -= RefreshButtons; RhSolutionsAddIn.Excel.WorkbookActivate -= RefreshButtons;
RhSolutionsAddIn.Excel.WorkbookDeactivate -= RefreshButtons;
RhSolutionsAddIn.Configuration.OnSettingsChange -= RefreshSettingTitle; RhSolutionsAddIn.Configuration.OnSettingsChange -= RefreshSettingTitle;
} }
@ -29,6 +31,7 @@ internal static class EventsUtil
RibbonController.RefreshControl("guess"); RibbonController.RefreshControl("guess");
RibbonController.RefreshControl("fillsleeves"); RibbonController.RefreshControl("fillsleeves");
RibbonController.RefreshControl("fillcouplings"); RibbonController.RefreshControl("fillcouplings");
RibbonController.RefreshControl("ocr");
} }
private static void RefreshExportButton(object sh, Range target) private static void RefreshExportButton(object sh, Range target)

View File

@ -1,19 +1,8 @@
#if !NET472 namespace RhSolutions.Tools;
using System.Runtime.Versioning;
#endif
namespace RhSolutions.Tools; internal class ExportTool : ReaderWriterTool, ITool
#if !NET472
[SupportedOSPlatform("windows")]
#endif
internal class ExportTool : Tool
{ {
public ExportTool(ReaderFactory readerFactory, WriterFactory writerFactory) : base(readerFactory, writerFactory) public void Execute()
{
}
public override void Execute()
{ {
Application app = RhSolutionsAddIn.Excel.Application; Application app = RhSolutionsAddIn.Excel.Application;
_reader = _readerFactory.GetReader("Excel"); _reader = _readerFactory.GetReader("Excel");
@ -22,4 +11,3 @@ internal class ExportTool : Tool
_writer.WriteProducts(products); _writer.WriteProducts(products);
} }
} }

View File

@ -1,17 +1,16 @@
namespace RhSolutions.Tools; namespace RhSolutions.Tools;
internal class FittingsTool : Tool internal class FittingsTool : ReaderWriterTool, ITool
{ {
private readonly FittingsCalculatorFactory _factory; private readonly FittingsCalculatorFactory _factory = RhSolutionsAddIn.ServiceProvider.GetService<FittingsCalculatorFactory>();
private string _calculatorName; private string _calculatorName;
public FittingsTool(ReaderFactory readerFactory, WriterFactory writerFactory, FittingsCalculatorFactory calculatorFactory, string calculatorName) : base(readerFactory, writerFactory) public FittingsTool(string calculatorName)
{ {
_factory = calculatorFactory;
_calculatorName = calculatorName; _calculatorName = calculatorName;
} }
public override void Execute() public void Execute()
{ {
Application app = RhSolutionsAddIn.Excel.Application; Application app = RhSolutionsAddIn.Excel.Application;
Worksheet worksheet = app.ActiveWorkbook.ActiveSheet; Worksheet worksheet = app.ActiveWorkbook.ActiveSheet;

View File

@ -1,16 +1,8 @@
#if !NET472 namespace RhSolutions.Tools;
using System.Runtime.Versioning;
#endif
namespace RhSolutions.Tools; internal class GuessTool : ReaderWriterTool, ITool
internal class GuessTool : Tool
{ {
public GuessTool(ReaderFactory readerFactory, WriterFactory writerFactory) : base(readerFactory, writerFactory) public void Execute()
{
}
public override void Execute()
{ {
Application app = RhSolutionsAddIn.Excel.Application; Application app = RhSolutionsAddIn.Excel.Application;
Worksheet worksheet = app.ActiveWorkbook.ActiveSheet; Worksheet worksheet = app.ActiveWorkbook.ActiveSheet;
@ -20,4 +12,3 @@ internal class GuessTool : Tool
_writer.WriteProducts(products); _writer.WriteProducts(products);
} }
} }

View File

@ -0,0 +1,9 @@
#if !NET472
#endif
namespace RhSolutions.Tools;
internal interface ITool: IDisposable
{
public void Execute();
}

View File

@ -1,19 +1,8 @@
#if !NET472 namespace RhSolutions.Tools;
using System.Runtime.Versioning;
#endif
namespace RhSolutions.Tools; internal class MergeTool : ReaderWriterTool, ITool
#if !NET472
[SupportedOSPlatform("windows")]
#endif
internal class MergeTool : Tool
{ {
public MergeTool(ReaderFactory readerFactory, WriterFactory writerFactory) : base(readerFactory, writerFactory) public void Execute()
{
}
public override void Execute()
{ {
IFileDialog dialog = RhSolutionsAddIn.ServiceProvider.GetRequiredService<IFileDialog>(); IFileDialog dialog = RhSolutionsAddIn.ServiceProvider.GetRequiredService<IFileDialog>();
string[] files = dialog.GetFiles(); string[] files = dialog.GetFiles();

View File

@ -1,25 +1,79 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using SnippingTool; using SnippingTool;
using System.Windows.Forms;
using Application = Microsoft.Office.Interop.Excel.Application;
namespace RhSolutions.Tools; namespace RhSolutions.Tools;
internal class OcrTool : Tool internal class OcrTool : ITool
{ {
public Application Application { get; set; } private IOcrClient client = RhSolutionsAddIn.ServiceProvider.GetService<IOcrClient>();
public OcrTool(ReaderFactory readerFactory, WriterFactory writerFactory, Application application) : base(readerFactory, writerFactory) private Application app = RhSolutionsAddIn.Excel;
{ private string xFolderId = RhSolutionsAddIn.Configuration["x-folder-id"];
Application = application; private string apiKey = RhSolutionsAddIn.Configuration["apiKey"];
}
public override void Execute() public async void Execute()
{ {
Application.Visible = false; try
{
RhSolutionsAddIn.Excel.Visible = false;
Task.Run(async delegate Task.Run(async delegate
{ {
await Task.Delay(100); await Task.Delay(250);
}).Wait(); }).Wait();
string shot = Snipper.SnipBase64(); string shot = Snipper.SnipBase64();
Application.Visible = true; RhSolutionsAddIn.Excel.Visible = true;
if (shot != null)
{
IEnumerable<object[,]> tables = await client.ProcessImage(shot);
if (tables != null)
{
foreach (var table in tables)
{
int rowCount = table.GetLength(0);
int columnCount = table.GetLength(1);
Range currentCell = app.ActiveCell;
Range tableRange = app.ActiveSheet.Range(currentCell,
app.ActiveSheet.Cells(currentCell.Row + rowCount - 1, currentCell.Column + columnCount - 1));
if (app.WorksheetFunction.CountA(tableRange) > 0)
{
MessageBox.Show(@"На листе отсустствует диапазон для вставки распознанной таблицы.Попробуйте в другом месте или на пустом листе.",
"Ошибка",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
RhSolutionsAddIn.Excel.Visible = true;
return;
}
tableRange.Borders.LineStyle = XlLineStyle.xlContinuous;
for (int row = 0; row < rowCount; row++)
for (int column = 0; column < columnCount; column++)
{
Range excelCell = app.ActiveSheet.Cells(currentCell.Row + row,
currentCell.Column + column);
excelCell.Value2 = table[row,column];
excelCell.EntireColumn.AutoFit();
excelCell.EntireRow.AutoFit();
}
app.ActiveSheet.Cells(currentCell.Row + rowCount + 1, currentCell.Column).Activate();
}
}
}
}
catch (Exception)
{
throw;
}
finally
{
RhSolutionsAddIn.Excel.Visible = true;
}
}
public void Dispose()
{
} }
} }

View File

@ -0,0 +1,15 @@
namespace RhSolutions.Tools;
internal abstract class ReaderWriterTool: IDisposable
{
protected IReader _reader;
protected IWriter _writer;
protected ReaderFactory _readerFactory = RhSolutionsAddIn.ServiceProvider.GetService<ReaderFactory>();
protected WriterFactory _writerFactory = RhSolutionsAddIn.ServiceProvider.GetService<WriterFactory>();
public void Dispose()
{
_reader?.Dispose();
_writer?.Dispose();
}
}

View File

@ -1,30 +0,0 @@
#if !NET472
using System.Runtime.Versioning;
#endif
namespace RhSolutions.Tools;
#if !NET472
[SupportedOSPlatform("windows")]
#endif
internal abstract class Tool : IDisposable
{
protected readonly ReaderFactory _readerFactory;
protected readonly WriterFactory _writerFactory;
protected IReader _reader;
protected IWriter _writer;
public Tool(ReaderFactory readerFactory, WriterFactory writerFactory)
{
_readerFactory = readerFactory;
_writerFactory = writerFactory;
}
public void Dispose()
{
_reader?.Dispose();
_writer?.Dispose();
}
public abstract void Execute();
}

View File

@ -2,25 +2,19 @@
internal class ToolFactory internal class ToolFactory
{ {
static ReaderFactory readerFactory = RhSolutionsAddIn.ServiceProvider.GetService<ReaderFactory>(); public ITool GetTool(string toolName)
static WriterFactory writerFactory = RhSolutionsAddIn.ServiceProvider.GetService<WriterFactory>();
static FittingsCalculatorFactory fittingsCalculatorFactory = RhSolutionsAddIn.ServiceProvider.GetService<FittingsCalculatorFactory>();
static Application application = RhSolutionsAddIn.ServiceProvider.GetService<Application>();
public Tool GetTool(string toolName)
{ {
Tool tool = toolName switch return toolName switch
{ {
"export" => new ExportTool(readerFactory, writerFactory), "export" => new ExportTool(),
"convert" => new ConvertTool(readerFactory, writerFactory), "convert" => new ConvertTool(),
"merge" => new MergeTool(readerFactory, writerFactory), "merge" => new MergeTool(),
"dxfexport" => new DxfTool(readerFactory, writerFactory), "dxfexport" => new DxfTool(),
"guess" => new GuessTool(readerFactory, writerFactory), "guess" => new GuessTool(),
"fillsleeves" => new FittingsTool(readerFactory, writerFactory, fittingsCalculatorFactory, "Sleeves"), "fillsleeves" => new FittingsTool("Sleeves"),
"fillcouplings" => new FittingsTool(readerFactory, writerFactory, fittingsCalculatorFactory, "Couplings"), "fillcouplings" => new FittingsTool("Couplings"),
"ocr" => new OcrTool(readerFactory, writerFactory, application), "ocr" => new OcrTool(),
_ => throw new Exception($"Неизвестный инструмент {toolName}"), _ => throw new Exception($"Неизвестный инструмент {toolName}"),
}; };
return tool;
} }
} }

View File

@ -33,6 +33,10 @@ Global
{DDB517C7-DF61-4C26-B691-956D0E5906C3}.Debug|Any CPU.Build.0 = Debug|Any CPU {DDB517C7-DF61-4C26-B691-956D0E5906C3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DDB517C7-DF61-4C26-B691-956D0E5906C3}.Release|Any CPU.ActiveCfg = Release|Any CPU {DDB517C7-DF61-4C26-B691-956D0E5906C3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DDB517C7-DF61-4C26-B691-956D0E5906C3}.Release|Any CPU.Build.0 = Release|Any CPU {DDB517C7-DF61-4C26-B691-956D0E5906C3}.Release|Any CPU.Build.0 = Release|Any CPU
{53F322B3-F477-4831-8E16-EA76934A0D59}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{53F322B3-F477-4831-8E16-EA76934A0D59}.Debug|Any CPU.Build.0 = Debug|Any CPU
{53F322B3-F477-4831-8E16-EA76934A0D59}.Release|Any CPU.ActiveCfg = Release|Any CPU
{53F322B3-F477-4831-8E16-EA76934A0D59}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE