PIbd-32_Artamonova_T.V._COP_2/COP/ExcelComponent.cs

74 lines
2.3 KiB
C#

using COP.Info;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.ComponentModel;
namespace COP
{
public partial class ExcelComponent : Component
{
public ExcelComponent()
{
InitializeComponent();
}
public ExcelComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void GenerateExcelWithImages(ExcelImageInfo info)
{
if (string.IsNullOrEmpty(info.fileName))
{
throw new ArgumentNullException(nameof(info.fileName), "File name cannot be null or empty.");
}
if (info.images == null || info.images.Count == 0)
{
throw new ArgumentException("At least one image must be provided.", nameof(info.images));
}
if (string.IsNullOrEmpty(info.documentTitle))
{
throw new ArgumentNullException(nameof(info.documentTitle), "Document title cannot be null or empty.");
}
var workbook = new XSSFWorkbook();
var sheet = workbook.CreateSheet("Sheet1");
sheet.CreateRow(0).CreateCell(0).SetCellValue(info.documentTitle);
int startRowIndex = 2;
var rowOffset = 1;
foreach (var imageInfo in info.images)
{
using var fs = new FileStream(imageInfo.FilePath, FileMode.Open, FileAccess.Read);
var imageBytes = new byte[fs.Length];
fs.Read(imageBytes, 0, imageBytes.Length);
var pictureIdx = workbook.AddPicture(imageBytes, PictureType.JPEG);
var drawing = sheet.CreateDrawingPatriarch();
var anchor = new XSSFClientAnchor(0, 0, 0, 0, 0, startRowIndex, 1, startRowIndex + 1);
var picture = drawing.CreatePicture(anchor, pictureIdx);
picture.Resize();
var pictureHeight = picture.GetImageDimension().Height / 20;
startRowIndex += pictureHeight + rowOffset;
}
using (var fs = new FileStream(info.fileName, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
}
public class ImageInfo
{
public string? FilePath { get; set; }
}
}
}