Второй компонент

This commit is contained in:
Максим Яковлев 2024-09-22 21:28:04 +04:00
parent 2caa860fb5
commit 554852a6b8
11 changed files with 283 additions and 4 deletions

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComponentProgramming.Components.Models
{
public class ColumnInfo
{
public string PropertyName;
public string Header;
public int Width;
public ColumnInfo(string propertyName, string header, int width)
{
PropertyName = propertyName;
Header = header;
Width = width;
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComponentProgramming.Components.Models
{
public class MergeCells
{
public string Header;
public int[] Indexes;
public MergeCells(string header, int[] indexes)
{
Header = header;
Indexes = indexes;
}
}
}

View File

@ -0,0 +1,36 @@
namespace ComponentProgramming.Components
{
partial class TableComponent
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@ -0,0 +1,146 @@
using ComponentProgramming.Components.Models;
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComponentProgramming.Components
{
public partial class TableComponent : Component
{
private Document? _document;
private Section? _section;
public TableComponent()
{
InitializeComponent();
}
public TableComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateTable<T>(string docPath, string title, List<MergeCells>? mergeCells, List<ColumnInfo> colInfo, List<T> data) where T : class, new()
{
if(string.IsNullOrEmpty(docPath))
{
throw new ArgumentNullException("Введите путь до файла!");
}
if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException("Введите заголовок");
}
if(colInfo == null)
{
throw new ArgumentNullException("Введите все заголовки");
}
if (data == null)
{
throw new ArgumentNullException("Нету информации для вывода");
}
_document = new Document();
var style = _document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
_section = _document.AddSection();
//Заголовок
var paragraph = _section.AddParagraph(title);
paragraph.Format.SpaceAfter = "0.3cm";
//Создание таблицы
var table = _section.AddTable();
table.Borders.Visible = true;
//Создание колонок
for(int i = 0; i < colInfo.Count; i++)
{
table.AddColumn(colInfo[i].Width);
}
//Создание строк
if(mergeCells != null)
{
table.AddRow();
}
var row = table.AddRow();
for (int i = 0; i < colInfo.Count; i++)
{
row[i].AddParagraph(colInfo[i].Header);
}
List<int> MergeColls = new List<int>();
//Объединение ячеек в строке
if(mergeCells != null)
{
foreach (var cell in mergeCells)
{
MergeColls.AddRange(cell.Indexes[1..]);
table.Rows[cell.Indexes[0]].Cells[cell.Indexes[1] - 1].MergeRight = cell.Indexes[2..].Length;
table.Rows[cell.Indexes[0]].Cells[cell.Indexes[1] - 1].AddParagraph(cell.Header);
}
}
int cellsCount = table.Rows[1].Cells.Count;
//Объединение ячеек в столбце
if (MergeColls.Count != 0)
{
for (int i = 0; i < cellsCount; i++)
{
var cell = table.Rows[0].Cells[i];
if (!MergeColls.Contains(i+1))
{
cell.MergeDown = 1;
cell.AddParagraph(colInfo[i].Header);
}
}
}
//Вывод данных
int rowData = 2;
foreach(var item in data)
{
var properties = item.GetType().GetProperties();
if(properties.Count() != cellsCount)
{
throw new Exception("Кол-во полей объекта не совпадает с кол-вом колонок");
}
for(int i = 0; i < properties.Count(); i++)
{
var property = properties[i];
var propValue = property.GetValue(item);
if (propValue == null) throw new Exception("Пустое поле");
if(property.Name == colInfo[i].PropertyName)
{
if (table.Rows.Count <= rowData) table.AddRow();
table.Rows[rowData].Cells[i].AddParagraph(propValue.ToString()!);
continue;
}
}
rowData++;
}
var renderer = new PdfDocumentRenderer(true);
renderer.Document = _document;
renderer.RenderDocument();
renderer.PdfDocument.Save(docPath);
}
}
}

View File

@ -34,7 +34,7 @@
buttonGetObj = new Button();
buttonEnter = new Button();
controlListBox = new ComponentProgramming.ControlListBox();
largeTextComponent = new ComponentProgramming.Components.LargeTextComponent(components);
tableComponent = new ComponentProgramming.Components.TableComponent(components);
SuspendLayout();
//
// controlComboBox
@ -108,6 +108,6 @@
private Button buttonGetObj;
private Button buttonEnter;
private ComponentProgramming.ControlListBox controlListBox;
private ComponentProgramming.Components.LargeTextComponent largeTextComponent;
private ComponentProgramming.Components.TableComponent tableComponent;
}
}

View File

@ -1,3 +1,5 @@
using ComponentProgramming.Components.Models;
namespace Forms
{
public partial class Form : System.Windows.Forms.Form
@ -9,7 +11,28 @@ namespace Forms
FillTextBox();
FillList();
string[] strings = new string[] { "У компонента должен быть публичный метод, который должен принимать на вход имя файла (включая путь до файла)", "название документа (заголовок в документе) и массив строк (каждая строка абзац текста в выходном документе или текст в ячейке для табличного документа)" };
largeTextComponent.CreateDocument("C:\\Users\\shotb\\source\\repos\\KOP\\ComponentProgramming\\Forms\\text.pdf", "Çàãîëîâîê", strings);
//largeTextComponent.CreateDocument("C:\\Users\\shotb\\source\\repos\\KOP\\ComponentProgramming\\Forms\\text.pdf", "Çàãîëîâîê", strings);
List<ColumnInfo> colInfos = new List<ColumnInfo>()
{
new ColumnInfo("Name","Èìÿ",50),
new ColumnInfo("Surname","Ôàìèëèÿ",100),
new ColumnInfo("Phone","Òåëåôîí",100),
new ColumnInfo("Email","Ïî÷òà",200),
new ColumnInfo("Password","Ïàðîëü",50),
};
List<MergeCells> mergeCells = new List<MergeCells>()
{
new MergeCells("Äàííûå", new int[] {0,3,4})
};
List<Worker> workers = new List<Worker>()
{
new Worker("Ñàøêà", "Èçîòîâ", "+88005553535", "mail@gmail.ru", "pass123"),
new Worker("Ñàøêà", "Òàáååâ", "+88005553535", "mail@gmail.ru", "pass123"),
new Worker("Âîâêà", "Êóçüìèí", "+88005553535", "mail@gmail.ru", "pass123"),
new Worker("Ãëåáóøêà", "Ìèîí÷èíñêèé", "+88005553535", "mail@gmail.ru", "pass123"),
};
tableComponent.CreateTable("C:\\Users\\shotb\\source\\repos\\KOP\\ComponentProgramming\\Forms\\table.pdf", "Çàãîëîâîê", mergeCells, colInfos, workers);
}
private void FillBox()

View File

@ -117,7 +117,7 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="largeTextComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<metadata name="tableComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Forms
{
public class Worker
{
public string Name { get; set; } = string.Empty;
public string Surname { get; set; } = string.Empty;
public string Phone { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public Worker() { }
public Worker(string name, string surname, string phone, string email, string password)
{
Name = name;
Surname = surname;
Phone = phone;
Email = email;
Password = password;
}
}
}

Binary file not shown.