PIbd-31_PotapovNS_COP_20/WinFormSolution/Components/ComponentExcelWithImage.cs

108 lines
3.3 KiB
C#
Raw Normal View History

using Excel = Microsoft.Office.Interop.Excel;
using System.ComponentModel;
namespace Components
{
public partial class ComponentExcelWithImage : Component
{
public ComponentExcelWithImage()
{
InitializeComponent();
}
public ComponentExcelWithImage(IContainer container) : this()
{
container.Add(this);
}
private void CheckInputValues(string filePath, string tableTitle, string[] imagePaths)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (string.IsNullOrEmpty(tableTitle))
{
throw new ArgumentNullException(nameof(tableTitle));
}
if (imagePaths == null)
{
throw new ArgumentNullException(nameof(imagePaths));
}
foreach (string imagePath in imagePaths)
{
if (string.IsNullOrEmpty(imagePath))
{
throw new ArgumentNullException("Image path is null");
}
}
}
public void CreateExcelWithImages(string filePath, string tableTitle, string[] imagePaths)
{
CheckInputValues(filePath, tableTitle, imagePaths);
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Sheets[1];
worksheet.Cells[1, 1] = tableTitle;
InsertImagesInSingleCell(worksheet, imagePaths, 2, 1);
workbook.SaveAs(filePath);
workbook.Close();
excelApp.Quit();
ReleaseObject(worksheet);
ReleaseObject(workbook);
ReleaseObject(excelApp);
}
private void InsertImagesInSingleCell(Excel.Worksheet worksheet, string[] imagePaths, int rowIndex, int columnIndex)
{
Excel.Range cell = worksheet.Cells[rowIndex, columnIndex];
double currentTopOffset = 0;
foreach (string imagePath in imagePaths)
{
if (File.Exists(imagePath))
{
Excel.Pictures pictures = (Excel.Pictures)worksheet.Pictures(System.Reflection.Missing.Value);
Excel.Picture picture = pictures.Insert(imagePath);
picture.Left = cell.Left;
picture.Top = cell.Top + currentTopOffset;
currentTopOffset += picture.Height;
}
else
{
throw new FileNotFoundException("Image not found at: " + imagePath);
}
}
}
private void ReleaseObject(object obj)
{
try
{
if (obj != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
}
catch (Exception ex)
{
obj = null;
2024-10-07 13:20:18 +04:00
Console.WriteLine("Error releasing object: " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}