RhSolutions-AddIn/RhSolutions.AddIn/Tools/OcrTool.cs

96 lines
2.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Threading.Tasks;
using SnippingTool;
using System.Windows.Forms;
using Application = Microsoft.Office.Interop.Excel.Application;
namespace RhSolutions.Tools;
internal class OcrTool : ITool
{
private IOcrClient client = RhSolutionsAddIn.ServiceProvider.GetService<IOcrClient>();
private Application app = RhSolutionsAddIn.Excel;
private string xFolderId = RhSolutionsAddIn.Configuration["x-folder-id"];
private string apiKey = RhSolutionsAddIn.Configuration["apiKey"];
public async void Execute()
{
try
{
RhSolutionsAddIn.Excel.Visible = false;
Task.Run(async delegate
{
await Task.Delay(250);
}).Wait();
string shot = Snipper.SnipBase64();
RhSolutionsAddIn.Excel.Visible = true;
if (shot != null)
{
IEnumerable<object[,]> tables = await client.ProcessImage(shot);
if (tables.Count() != 0)
{
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];
}
foreach (Range row in tableRange.Rows)
{
row.EntireRow.AutoFit();
}
foreach (Range column in tableRange.Columns)
{
column.EntireColumn.AutoFit();
}
app.ActiveSheet.Cells(currentCell.Row + rowCount + 1, currentCell.Column).Activate();
}
}
else
{
MessageBox.Show(@"В выделенном фрагменте не распознано ни одной таблицы.",
"Ошибка",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
RhSolutionsAddIn.Excel.Visible = true;
return;
}
}
}
catch (Exception)
{
throw;
}
finally
{
RhSolutionsAddIn.Excel.Visible = true;
}
}
public void Dispose()
{
}
}