PIbd-32_Shabunov_O.A._COP/ShabComponentsLibrary/ShabConfigurableTableComponent.cs

96 lines
2.8 KiB
C#
Raw Normal View History

2024-09-24 23:54:36 +04:00
using ShabComponentsLibrary.OfficePackage;
using ShabComponentsLibrary.OfficePackage.HelperEnums;
using ShabComponentsLibrary.OfficePackage.HelperModels;
using System.ComponentModel;
namespace ShabComponentsLibrary
{
/// <summary>
/// Невизуальный компонент для создания документа с таблицей,
/// у которой шапкой является первая строка и первый столбец
/// </summary>
public partial class ShabConfigurableTableComponent : Component
{
public ShabConfigurableTableComponent()
{
InitializeComponent();
}
public ShabConfigurableTableComponent(IContainer Container)
{
Container.Add(this);
InitializeComponent();
}
public void CreateDocument<T>(string Filename, string Title,
List<(double ColumnWidth, string TableHeader, string HeaderPropertyName)> ColumnData,
List<double> RowHeights, List<T> Data)
2024-09-24 23:54:36 +04:00
{
if (string.IsNullOrEmpty(Filename))
throw new ArgumentException("Filename cannot be empty");
if (string.IsNullOrEmpty(Title))
throw new ArgumentException("Title cannot be empty");
if (ColumnData.Count == 0)
2024-09-24 23:54:36 +04:00
throw new ArgumentException("Headers cannot be empty");
if (Data.Count == 0)
throw new ArgumentException("Data cannot be empty");
if (RowHeights.Count != 2)
throw new ArgumentException("Row heights should be specified for header row and other rows");
SaveToPdf Pdf = new SaveToPdf();
Pdf.CreatePdf();
Pdf.CreateParagraph(new PdfParagraph
{
Text = Title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
Pdf.CreateTable(ColumnData.Select(x => x.ColumnWidth).ToList());
2024-09-24 23:54:36 +04:00
// Шапка
Pdf.CreateRow(new PdfRowParameters
{
Texts = ColumnData.Select(x => x.TableHeader).ToList(),
2024-09-24 23:54:36 +04:00
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center,
RowHeight = RowHeights[0]
});
// Данные
foreach (var Object in Data)
{
List<string> Cells = new List<string>();
for (int ColumnIndex = 0; ColumnIndex < ColumnData.Count; ++ColumnIndex)
2024-09-24 23:54:36 +04:00
{
string PropertyName = ColumnData[ColumnIndex].HeaderPropertyName;
2024-09-24 23:54:36 +04:00
var Property = typeof(T).GetProperty(PropertyName);
if (Property is null)
{
throw new ArgumentException($"Failed to find property {PropertyName} in provided objects class");
}
var PropertyValue = Property.GetValue(Object)?.ToString();
if (PropertyValue is not null)
{
Cells.Add(PropertyValue);
}
}
Pdf.CreateRow(new PdfRowParameters
{
Texts = Cells,
Style = "Normal",
FirstCellStyle = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Left,
FirstCellParagraphAlignment = PdfParagraphAlignmentType.Center,
RowHeight = RowHeights[1]
});
}
Pdf.SavePdf(Filename);
}
}
}