4 Commits

Author SHA1 Message Date
Вячеслав Иванов
5012607047 DOOOOOONE 2024-09-19 15:51:42 +04:00
Вячеслав Иванов
ce985d3b60 fix 2024-09-18 23:44:58 +04:00
Вячеслав Иванов
7ce94d7ae7 laba 2 2024-09-15 20:16:55 +04:00
Вячеслав Иванов
3058978306 done 2024-09-06 00:05:36 +04:00
36 changed files with 2752 additions and 0 deletions

231
KOP/Ivanov_App/Form.Designer.cs generated Normal file
View File

@@ -0,0 +1,231 @@
namespace Ivanov_App
{
partial class Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
ItemList = new Ivanov_visual_components.ItemList();
ButtonListClear = new Button();
ButtonLoadList = new Button();
dateBoxWithNull = new Ivanov_visual_components.DateBoxWithNull();
ButtonGetValue = new Button();
ButtonSetValue = new Button();
itemTable = new Ivanov_visual_components.ItemTable();
ButtonClear = new Button();
textBoxEvent = new TextBox();
ButtonAdd = new Button();
ButtonSel = new Button();
this.excelTable = new Ivanov_components.ExcelTable(this.components);
this.buttonExcel = new System.Windows.Forms.Button();
this.excelSaveHeader = new System.Windows.Forms.Button();
this.SaveBar = new System.Windows.Forms.Button();
this.excelWithCustomTable = new Ivanov_components.ExcelWithCustomTable(this.components);
this.excelGistogram = new Ivanov_components.ExcelGistogram(this.components);
SuspendLayout();
//
// ItemList
//
this.ItemList.Location = new System.Drawing.Point(12, 12);
this.ItemList.Name = "ItemList";
this.ItemList.SelectedElement = "";
this.ItemList.Size = new System.Drawing.Size(210, 212);
this.ItemList.TabIndex = 0;
this.ItemList.ChangeEvent += new System.EventHandler(this.ItemList_ChangeEvent);
//
// ButtonListClear
//
this.ButtonListClear.Location = new System.Drawing.Point(12, 230);
this.ButtonListClear.Name = "ButtonListClear";
this.ButtonListClear.Size = new System.Drawing.Size(210, 23);
this.ButtonListClear.TabIndex = 1;
this.ButtonListClear.Text = "List Clear";
this.ButtonListClear.UseVisualStyleBackColor = true;
this.ButtonListClear.Click += new System.EventHandler(this.ButtonListClear_Click);
//
// ButtonLoadList
//
this.ButtonLoadList.Location = new System.Drawing.Point(12, 259);
this.ButtonLoadList.Name = "ButtonLoadList";
this.ButtonLoadList.Size = new System.Drawing.Size(210, 23);
this.ButtonLoadList.TabIndex = 2;
this.ButtonLoadList.Text = "Load List";
this.ButtonLoadList.UseVisualStyleBackColor = true;
this.ButtonLoadList.Click += new System.EventHandler(this.ButtonLoadList_Click);
//
// dateBoxWithNull
//
this.dateBoxWithNull.BackColor = System.Drawing.SystemColors.ControlLight;
this.dateBoxWithNull.Location = new System.Drawing.Point(228, 12);
this.dateBoxWithNull.Name = "dateBoxWithNull";
this.dateBoxWithNull.Size = new System.Drawing.Size(147, 29);
this.dateBoxWithNull.TabIndex = 3;
this.dateBoxWithNull.Value = null;
this.dateBoxWithNull.CheckBoxEvent += new System.EventHandler(this.dateBoxWithNull1_CheckBoxEvent);
this.dateBoxWithNull.ChangeEvent += new System.EventHandler(this.dateBoxWithNull1_ChangeEvent);
//
// ButtonGetValue
//
this.ButtonGetValue.Location = new System.Drawing.Point(228, 47);
this.ButtonGetValue.Name = "ButtonGetValue";
this.ButtonGetValue.Size = new System.Drawing.Size(147, 23);
this.ButtonGetValue.TabIndex = 4;
this.ButtonGetValue.Text = "Get Value";
this.ButtonGetValue.UseVisualStyleBackColor = true;
this.ButtonGetValue.Click += new System.EventHandler(this.ButtonGetValue_Click);
//
// ButtonSetValue
//
this.ButtonSetValue.Location = new System.Drawing.Point(228, 76);
this.ButtonSetValue.Name = "ButtonSetValue";
this.ButtonSetValue.Size = new System.Drawing.Size(147, 23);
this.ButtonSetValue.TabIndex = 5;
this.ButtonSetValue.Text = "Set Value";
this.ButtonSetValue.UseVisualStyleBackColor = true;
this.ButtonSetValue.Click += new System.EventHandler(this.ButtonSetValue_Click);
//
// itemTable
//
this.itemTable.Location = new System.Drawing.Point(381, 12);
this.itemTable.Name = "itemTable";
this.itemTable.Size = new System.Drawing.Size(548, 426);
this.itemTable.TabIndex = 6;
//
// ButtonClear
//
this.ButtonClear.Location = new System.Drawing.Point(935, 12);
this.ButtonClear.Name = "ButtonClear";
this.ButtonClear.Size = new System.Drawing.Size(94, 23);
this.ButtonClear.TabIndex = 7;
this.ButtonClear.Text = "Table clear";
this.ButtonClear.UseVisualStyleBackColor = true;
this.ButtonClear.Click += new System.EventHandler(this.ButtonClear_Click);
//
// textBoxEvent
//
this.textBoxEvent.Location = new System.Drawing.Point(228, 105);
this.textBoxEvent.Name = "textBoxEvent";
this.textBoxEvent.Size = new System.Drawing.Size(147, 23);
this.textBoxEvent.TabIndex = 8;
//
// ButtonAdd
//
this.ButtonAdd.Location = new System.Drawing.Point(935, 41);
this.ButtonAdd.Name = "ButtonAdd";
this.ButtonAdd.Size = new System.Drawing.Size(94, 23);
this.ButtonAdd.TabIndex = 9;
this.ButtonAdd.Text = "Table Add";
this.ButtonAdd.UseVisualStyleBackColor = true;
this.ButtonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// ButtonSel
//
this.ButtonSel.Location = new System.Drawing.Point(935, 70);
this.ButtonSel.Name = "ButtonSel";
this.ButtonSel.Size = new System.Drawing.Size(94, 23);
this.ButtonSel.TabIndex = 10;
this.ButtonSel.Text = "Get Value";
this.ButtonSel.UseVisualStyleBackColor = true;
this.ButtonSel.Click += new System.EventHandler(this.ButtonSel_Click);
//
// buttonExcel
//
this.buttonExcel.Location = new System.Drawing.Point(12, 415);
this.buttonExcel.Name = "buttonExcel";
this.buttonExcel.Size = new System.Drawing.Size(75, 23);
this.buttonExcel.TabIndex = 11;
this.buttonExcel.Text = "Excel Save";
this.buttonExcel.UseVisualStyleBackColor = true;
this.buttonExcel.Click += new System.EventHandler(this.buttonExcel_Click);
//
// excelSaveHeader
//
this.excelSaveHeader.Location = new System.Drawing.Point(93, 415);
this.excelSaveHeader.Name = "excelSaveHeader";
this.excelSaveHeader.Size = new System.Drawing.Size(129, 23);
this.excelSaveHeader.TabIndex = 12;
this.excelSaveHeader.Text = "Save With Header";
this.excelSaveHeader.UseVisualStyleBackColor = true;
this.excelSaveHeader.Click += new System.EventHandler(this.excelSaveHeader_Click);
//
// SaveBar
//
this.SaveBar.Location = new System.Drawing.Point(228, 415);
this.SaveBar.Name = "SaveBar";
this.SaveBar.Size = new System.Drawing.Size(147, 23);
this.SaveBar.TabIndex = 13;
this.SaveBar.Text = "Save Bar";
this.SaveBar.UseVisualStyleBackColor = true;
this.SaveBar.Click += new System.EventHandler(this.SaveBar_Click);
//
// Form
//
AutoScaleDimensions = new SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
ClientSize = new Size(1041, 450);
Controls.Add(SaveBar);
Controls.Add(excelSaveHeader);
Controls.Add(buttonExcel);
Controls.Add(ButtonSel);
Controls.Add(ButtonAdd);
Controls.Add(textBoxEvent);
Controls.Add(ButtonClear);
Controls.Add(itemTable);
Controls.Add(ButtonSetValue);
Controls.Add(ButtonGetValue);
Controls.Add(dateBoxWithNull);
Controls.Add(ButtonLoadList);
Controls.Add(ButtonListClear);
Controls.Add(ItemList);
Margin = new Padding(6);
Name = "Form";
Text = "Form1";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Ivanov_visual_components.ItemList ItemList;
private Button ButtonListClear;
private Button ButtonLoadList;
private Ivanov_visual_components.DateBoxWithNull dateBoxWithNull;
private Button ButtonGetValue;
private Button ButtonSetValue;
private Ivanov_visual_components.ItemTable itemTable;
private Button ButtonClear;
private TextBox textBoxEvent;
private Button ButtonAdd;
private Button ButtonSel;
private Ivanov_components.ExcelTable excelTable;
private Button buttonExcel;
private Button excelSaveHeader;
private Button SaveBar;
private Ivanov_components.ExcelWithCustomTable excelWithCustomTable;
private Ivanov_components.ExcelGistogram excelGistogram;
}
}

189
KOP/Ivanov_App/Form.cs Normal file
View File

@@ -0,0 +1,189 @@
using Ivanov_components.Models;
using Microsoft.VisualBasic.Devices;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Header;
namespace Ivanov_App
{
public partial class Form : System.Windows.Forms.Form
{
public Form()
{
InitializeComponent();
CreateList();
}
// 1 компонент
private void CreateList()
{
for (int i = 0; i < 10; i++)
{
ItemList.Items.Add($"Item-{i}");
}
}
private void ButtonListClear_Click(object sender, EventArgs e)
{
ItemList.Clear();
}
private void ButtonLoadList_Click(object sender, EventArgs e)
{
CreateList();
}
private void ItemList_ChangeEvent(object sender, EventArgs e)
{
object? selectedItem = ItemList.SelectedElement;
MessageBox.Show($"Change selected item {selectedItem?.ToString()}");
}
// 2 компонент
private void dateBoxWithNull1_ChangeEvent(object sender, EventArgs e)
{
textBoxEvent.Text = "TextBox change";
}
private void dateBoxWithNull1_CheckBoxEvent(object sender, EventArgs e)
{
textBoxEvent.Text = "CheckBox change";
}
private void ButtonGetValue_Click(object sender, EventArgs e)
{
MessageBox.Show($"Value is {dateBoxWithNull.Value}");
}
private bool EmptyFill = false;
private void ButtonSetValue_Click(object sender, EventArgs e)
{
if (EmptyFill)
{
dateBoxWithNull.Value = DateTime.Now;
}
else
{
dateBoxWithNull.Value = null;
}
EmptyFill = !EmptyFill;
}
// 3 компонент
readonly List<Student> students = new()
{
new Student { Id = 0, Name = "Петя", Surname = "Петров", Course = 1 },
new Student { Id = 1, Name = "Ваня", Surname = "Пупкин", Course = 2 },
new Student { Id = 2, Name = "Женя", Surname = "Львов", Course = 3 },
new Student { Id = 3, Name = "Коля", Surname = "Серов", Course = 4 },
new Student { Id = 4, Name = "Максим", Surname = "Ершов", Course = 5 }
};
private void CreateTable()
{
itemTable.ConfigColumn(new()
{
ColumnsCount = 4,
NameColumn = new string[] { "Id", "Name", "Surname", "Course" },
Width = new int[] { 10, 150, 250, 200 },
Visible = new bool[] { false, true, true, true, true },
PropertiesObject = new string[] { "Id", "Name", "Surname", "Course" }
});
foreach (Student computer in students)
{
for (int i = 0; i < 4; i++)
{
itemTable.AddItem(computer, computer.Id, i);
itemTable.Update();
}
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
CreateTable();
}
private void ButtonClear_Click(object sender, EventArgs e)
{
itemTable.ClearDataGrid();
}
private void ButtonSel_Click(object sender, EventArgs e)
{
Student? computer = itemTable.GetSelectedObjectInRow<Student>();
if (computer is null) return;
MessageBox.Show($"{computer.Id}-{computer.Name}-{computer.Surname}-{computer.Course}");
}
// 2 лаба
private void buttonExcel_Click(object sender, EventArgs e)
{
((Control)sender).BackColor = Color.White;
excelTable.CreateDoc(new TableConfig
{
FilePath = "table.xlsx",
Header = "Example",
Data = new List<string[,]>
{
new string[,] {
{ "1", "1", "1" },
{ "1", "2", "2" },
{ "1", "3", "3" }
},
new string[,] {
{ "", "", "" },
},
new string[,] {
{ "2", "2", "2" },
{ "3", "3", "3" },
{ "4", "4", "4" }
},
}
});
((Control)sender).BackColor = Color.Green;
}
private void excelSaveHeader_Click(object sender, EventArgs e)
{
((Control)sender).BackColor = Color.White;
excelWithCustomTable.CreateDoc(new TableWithHeaderConfig<Student>
{
FilePath = "header.xlsx",
Header = "Students",
ColumnsRowsWidth = new List<(int Column, int Row)> { (5, 5), (10, 5), (10, 0), (5, 0), (7, 0) },
Headers = new List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)>
{
(0, 0, "Id", "Id"),
(1, 0, "Name", "Name"),
(2, 0, "Surname", "Surname"),
(3, 0, "Course", "Course"),
},
Data = students,
});
((Control)sender).BackColor = Color.Green;
}
private void SaveBar_Click(object sender, EventArgs e)
{
((Control)sender).BackColor = Color.White;
var rnd = new Random();
excelGistogram.CreateDoc(new ChartConfig
{
FilePath = "bar.xlsx",
Header = "Chart",
ChartTitle = "BarChart",
LegendLocation = Ivanov_components.Models.Location.Top,
Data = new Dictionary<string, List<(string Name, double Value)>>
{
{ "Series 1", new() { ("Один", rnd.Next()), ("Два", rnd.Next()), ("Три", rnd.Next()) } }
}
});
((Control)sender).BackColor = Color.Green;
}
}
}

120
KOP/Ivanov_App/Form.resx Normal file
View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Ivanov_components\Ivanov_components.csproj" />
<ProjectReference Include="..\Ivanov_visual_components\Ivanov_visual_components.csproj" />
</ItemGroup>
</Project>

17
KOP/Ivanov_App/Program.cs Normal file
View File

@@ -0,0 +1,17 @@
namespace Ivanov_App
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form());
}
}
}

26
KOP/Ivanov_App/Student.cs Normal file
View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ivanov_App
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Surname { get; set; } = string.Empty;
public int Course { get; set; }
public Student(int id, string name, string surname, int course)
{
Id = id;
Name = name;
Surname = surname;
Course = course;
}
public Student() { }
}
}

View File

@@ -0,0 +1,36 @@
namespace Ivanov_components
{
partial class ExcelGistogram
{
/// <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,29 @@
using Ivanov_components.Helpers;
using Ivanov_components.Models;
using System.ComponentModel;
namespace Ivanov_components
{
public partial class ExcelGistogram : Component
{
public ExcelGistogram()
{
InitializeComponent();
}
public ExcelGistogram(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateDoc(ChartConfig config)
{
config.CheckFields();
IContext creator = new WorkWithExcel();
creator.CreateHeader(config.Header);
creator.CreateBarChart(config);
creator.SaveDoc(config.FilePath);
}
}
}

View File

@@ -0,0 +1,36 @@
namespace Ivanov_components
{
partial class ExcelTable
{
/// <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,36 @@
using Ivanov_components.Helpers;
using Ivanov_components.Models;
using System.ComponentModel;
namespace Ivanov_components
{
public partial class ExcelTable : Component
{
public ExcelTable()
{
InitializeComponent();
}
public ExcelTable(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateDoc(TableConfig config)
{
config.CheckFields();
IContext creator = new WorkWithExcel();
creator.CreateHeader(config.Header);
if (config.Data != null)
{
foreach (var datum in config.Data)
{
creator.CreateTable(datum);
}
}
creator.SaveDoc(config.FilePath);
}
}
}

View File

@@ -0,0 +1,36 @@
namespace Ivanov_components
{
partial class ExcelWithCustomTable
{
/// <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,54 @@
using Ivanov_components.Helpers;
using Ivanov_components.Models;
using System.ComponentModel;
namespace Ivanov_components
{
public partial class ExcelWithCustomTable : Component
{
public ExcelWithCustomTable()
{
InitializeComponent();
}
public ExcelWithCustomTable(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateDoc<T>(TableWithHeaderConfig<T> config)
{
config.CheckFields();
config.ColumnsRowsDataCount = (config.ColumnsRowsWidth.Count, config.Data.Count + 1);
IContext creator = new WorkWithExcel();
creator.CreateHeader(config.Header);
creator.CreateTableWithHeader();
creator.CreateMultiHeader(config);
var array = new string[config.Data.Count, config.Headers.Count];
for (var j = 0; j < config.Data.Count; j++)
{
for (var i = 0; i < config.Headers.Count; i++)
{
(int, int, string, string) first = (0, 0, null, null)!;
foreach (var x in config.Headers.Where(x => x.ColumnIndex == i))
{
first = x;
break;
}
var (_, _, _, name) = first;
if (name != null)
{
object? value = config.Data[j]?.GetType().GetProperty(name)!.GetValue(config.Data[j], null);
array[j, i] = value?.ToString() ?? string.Empty;
}
}
}
creator.LoadDataToTableWithMultiHeader(array, config.ColumnsRowsWidth[1].Row);
creator.SaveDoc(config.FilePath);
}
}
}

View File

@@ -0,0 +1,453 @@
using System.Globalization;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
using Ivanov_components.Models;
using static System.String;
using Index = DocumentFormat.OpenXml.Drawing.Charts.Index;
using Orientation = DocumentFormat.OpenXml.Drawing.Charts.Orientation;
namespace Ivanov_components.Helpers
{
public static class ChartGenerator
{
private static uint _order;
private static uint _index = 1u;
public static DocumentFormat.OpenXml.Drawing.Charts.Chart GenerateBarChart(ChartConfig config)
{
var axisId = new AxisId
{
Val = (UInt32Value)97045504u
};
var axisId2 = new AxisId
{
Val = (UInt32Value)97055488u
};
var barChart = new BarChart();
barChart.Append(new BarDirection
{
Val = (EnumValue<BarDirectionValues>)BarDirectionValues.Column
});
barChart.Append(new BarGrouping
{
Val = (EnumValue<BarGroupingValues>)BarGroupingValues.Clustered
});
if (config.Data != null)
{
barChart.Append(
GenerateBarChartSeries(config.Data.First().Key, config.Data.First().Value));
}
barChart.Append(axisId);
barChart.Append(axisId2);
var outline = new Outline
{
Width = (Int32Value)25400
};
outline.Append(new NoFill());
var shapeProperties = new DocumentFormat.OpenXml.Drawing.Charts.ShapeProperties();
shapeProperties.Append(new NoFill());
shapeProperties.Append(outline);
var plotArea = new PlotArea();
plotArea.Append(new Layout());
plotArea.Append(barChart);
plotArea.Append(GenerateCategoryAxis(axisId, AxisPositionValues.Bottom, axisId2));
plotArea.Append(GenerateValueAxis(axisId2, AxisPositionValues.Left, axisId));
plotArea.Append(shapeProperties);
return GenerateChart(config.ChartTitle, plotArea, config.LegendLocation);
}
private static DocumentFormat.OpenXml.Drawing.Charts.Chart GenerateChart(
string titleText,
OpenXmlElement plotArea,
Location legendLocation)
{
var chart = new DocumentFormat.OpenXml.Drawing.Charts.Chart();
if (IsNullOrWhiteSpace(titleText))
{
chart.Append(GenerateTitle(titleText));
}
else
{
chart.Append(new AutoTitleDeleted
{
Val = (BooleanValue)true
});
}
var position = legendLocation switch
{
Location.Top => LegendPositionValues.Top,
Location.Right => LegendPositionValues.Right,
Location.Left => LegendPositionValues.Left,
_ => LegendPositionValues.Bottom,
};
chart.Append(plotArea);
chart.Append(GenerateLegend(position));
chart.Append(new PlotVisibleOnly
{
Val = (BooleanValue)true
});
return chart;
}
private static Title GenerateTitle(string titleText)
{
var run = new Run();
run.Append(new RunProperties
{
FontSize = (Int32Value)1100
});
run.Append(new Text(titleText));
var paragraphProperties = new ParagraphProperties();
paragraphProperties.Append(new DefaultRunProperties
{
FontSize = (Int32Value)1100
});
var paragraph = new Paragraph();
paragraph.Append(paragraphProperties);
paragraph.Append(run);
var richText = new RichText();
richText.Append(new BodyProperties());
richText.Append(new ListStyle());
richText.Append(paragraph);
var chartText = new ChartText();
chartText.Append(richText);
var title = new Title();
title.Append(chartText);
title.Append(new Layout());
title.Append(new Overlay
{
Val = (BooleanValue)false
});
return title;
}
private static BarChartSeries GenerateBarChartSeries(
string seriesName,
IReadOnlyCollection<(string Name, double Value)> data)
{
var barChartSeries = new BarChartSeries();
barChartSeries.Append(new Index
{
Val = (UInt32Value)_index
});
barChartSeries.Append(new Order
{
Val = (UInt32Value)_order
});
barChartSeries.Append(GenerateSeriesText(seriesName));
barChartSeries.Append(GenerateCategoryAxisData(data.Select(c => c.Name).ToArray()));
barChartSeries.Append(GenerateValues(data.Select(v => v.Value).ToArray()));
_index++; _order++;
return barChartSeries;
}
private static SeriesText GenerateSeriesText(string seriesName)
{
var stringPoint = new StringPoint
{
Index = (UInt32Value)0u
};
stringPoint.Append(new NumericValue
{
Text = seriesName
});
var stringCache = new StringCache();
stringCache.Append(new PointCount
{
Val = (UInt32Value)1u
});
stringCache.Append(stringPoint);
var stringReference = new StringReference();
stringReference.Append(stringCache);
var seriesText = new SeriesText();
seriesText.Append(stringReference);
return seriesText;
}
private static CategoryAxisData GenerateCategoryAxisData(IReadOnlyList<string> data)
{
var num = (uint)data.Count;
var stringCache = GenerateStringCache(num);
for (var num2 = 0u; num2 < num; num2++)
{
stringCache.Append(GenerateStringPoint(num2, data[(int)num2]));
}
var stringReference = new StringReference();
stringReference.Append(stringCache);
var categoryAxisData = new CategoryAxisData();
categoryAxisData.Append(stringReference);
return categoryAxisData;
}
private static Values GenerateValues(double[] data)
{
var num = (uint)data.Length;
var numberingCache = GenerateNumberingCache(num);
for (var num2 = 0u; num2 < num; num2++)
{
numberingCache.Append(GenerateNumericPoint(num2, data[num2]
.ToString(CultureInfo.CurrentCulture)));
}
var numberReference = new NumberReference();
numberReference.Append(numberingCache);
var values = new Values();
values.Append(numberReference);
return values;
}
private static NumberingCache GenerateNumberingCache(uint numPoints)
{
var numberingCache = new NumberingCache();
numberingCache.Append(new FormatCode
{
Text = "General"
});
numberingCache.Append(new PointCount
{
Val = (UInt32Value)numPoints
});
return numberingCache;
}
private static StringCache GenerateStringCache(uint numPoints)
{
var stringCache = new StringCache();
stringCache.Append(new PointCount
{
Val = (UInt32Value)numPoints
});
return stringCache;
}
private static NumericPoint GenerateNumericPoint(UInt32Value idx, string text)
{
var numericPoint = new NumericPoint
{
Index = idx
};
numericPoint.Append(new NumericValue
{
Text = text
});
return numericPoint;
}
private static StringPoint GenerateStringPoint(UInt32Value idx, string text)
{
var stringPoint = new StringPoint
{
Index = idx
};
stringPoint.Append(new NumericValue
{
Text = text
});
return stringPoint;
}
private static CategoryAxis GenerateCategoryAxis(
UnsignedIntegerType axisId,
AxisPositionValues axisPosition,
UnsignedIntegerType crossingAxisId)
{
var scaling = new Scaling();
scaling.Append(new Orientation
{
Val = (EnumValue<OrientationValues>)OrientationValues.MinMax
});
var solidFill = new SolidFill();
solidFill.Append(new RgbColorModelHex
{
Val = (HexBinaryValue)"000000"
});
var defaultRunProperties = new DefaultRunProperties
{
FontSize = (Int32Value)1000,
Bold = (BooleanValue)false,
Italic = (BooleanValue)false,
Underline = (EnumValue<TextUnderlineValues>)TextUnderlineValues.None,
Strike = (EnumValue<TextStrikeValues>)TextStrikeValues.NoStrike,
Baseline = (Int32Value)0
};
defaultRunProperties.Append(solidFill);
var paragraphProperties = new ParagraphProperties();
paragraphProperties.Append(defaultRunProperties);
var paragraph = new Paragraph();
paragraph.Append(paragraphProperties);
paragraph.Append(new EndParagraphRunProperties());
var textProperties = new TextProperties();
textProperties.Append(new BodyProperties
{
Rotation = (Int32Value)(-1800000),
Vertical = (EnumValue<TextVerticalValues>)TextVerticalValues.Horizontal
});
textProperties.Append(new ListStyle());
textProperties.Append(paragraph);
var categoryAxis = new CategoryAxis();
categoryAxis.Append(new AxisId
{
Val = axisId.Val
});
categoryAxis.Append(scaling);
categoryAxis.Append(new AxisPosition
{
Val = (EnumValue<AxisPositionValues>)axisPosition
});
categoryAxis.Append(new NumberingFormat
{
FormatCode = (StringValue)"General",
SourceLinked = (BooleanValue)true
});
categoryAxis.Append(new TickLabelPosition
{
Val = (EnumValue<TickLabelPositionValues>)TickLabelPositionValues.Low
});
categoryAxis.Append(GenerateChartShapeProperties(3175));
categoryAxis.Append(textProperties);
categoryAxis.Append(new CrossingAxis
{
Val = crossingAxisId.Val
});
categoryAxis.Append(new Crosses
{
Val = (EnumValue<CrossesValues>)CrossesValues.AutoZero
});
categoryAxis.Append(new AutoLabeled
{
Val = (BooleanValue)true
});
categoryAxis.Append(new LabelAlignment
{
Val = (EnumValue<LabelAlignmentValues>)LabelAlignmentValues.Center
});
categoryAxis.Append(new LabelOffset
{
Val = (UInt16Value)(ushort)100
});
categoryAxis.Append(new TickLabelSkip
{
Val = (Int32Value)1
});
categoryAxis.Append(new TickMarkSkip
{
Val = (Int32Value)1
});
return categoryAxis;
}
private static ValueAxis GenerateValueAxis(
UnsignedIntegerType axisId,
AxisPositionValues position,
UnsignedIntegerType crossingAxisId)
{
var scaling = new Scaling();
scaling.Append(new Orientation
{
Val = (EnumValue<OrientationValues>)OrientationValues.MinMax
});
var paragraphProperties = new ParagraphProperties();
paragraphProperties.Append(new DefaultRunProperties());
var paragraph = new Paragraph();
paragraph.Append(paragraphProperties);
paragraph.Append(new EndParagraphRunProperties());
var textProperties = new TextProperties();
textProperties.Append(new BodyProperties());
textProperties.Append(new ListStyle());
textProperties.Append(paragraph);
var valueAxis = new ValueAxis();
valueAxis.Append(new AxisId
{
Val = axisId.Val
});
valueAxis.Append(scaling);
valueAxis.Append(new Delete
{
Val = (BooleanValue)false
});
valueAxis.Append(new AxisPosition
{
Val = (EnumValue<AxisPositionValues>)position
});
valueAxis.Append(new MajorGridlines());
valueAxis.Append(new NumberingFormat
{
FormatCode = (StringValue)"General",
SourceLinked = (BooleanValue)false
});
valueAxis.Append(new MajorTickMark
{
Val = (EnumValue<TickMarkValues>)TickMarkValues.None
});
valueAxis.Append(new TickLabelPosition
{
Val = (EnumValue<TickLabelPositionValues>)TickLabelPositionValues.NextTo
});
valueAxis.Append(GenerateChartShapeProperties(9525));
valueAxis.Append(textProperties);
valueAxis.Append(new CrossingAxis
{
Val = crossingAxisId.Val
});
valueAxis.Append(new Crosses
{
Val = (EnumValue<CrossesValues>)CrossesValues.AutoZero
});
valueAxis.Append(new CrossBetween
{
Val = (EnumValue<CrossBetweenValues>)CrossBetweenValues.Between
});
return valueAxis;
}
private static ChartShapeProperties GenerateChartShapeProperties(int width)
{
var solidFill = new SolidFill();
solidFill.Append(new RgbColorModelHex
{
Val = (HexBinaryValue)"000000"
});
var outline = new Outline
{
Width = (Int32Value)width
};
outline.Append(solidFill);
outline.Append(new PresetDash
{
Val = (EnumValue<PresetLineDashValues>)PresetLineDashValues.Solid
});
var chartShapeProperties = new ChartShapeProperties();
chartShapeProperties.Append(outline);
return chartShapeProperties;
}
private static Legend GenerateLegend(LegendPositionValues position)
{
var paragraphProperties = new ParagraphProperties();
paragraphProperties.Append(new DefaultRunProperties());
var paragraph = new Paragraph();
paragraph.Append(paragraphProperties);
paragraph.Append(new EndParagraphRunProperties());
var textProperties = new TextProperties();
textProperties.Append(new BodyProperties());
textProperties.Append(new ListStyle());
textProperties.Append(paragraph);
var legend = new Legend();
legend.Append(new LegendPosition
{
Val = (EnumValue<LegendPositionValues>)position
});
legend.Append(new Layout());
legend.Append(new Overlay
{
Val = (BooleanValue)false
});
legend.Append(textProperties);
return legend;
}
}
}

View File

@@ -0,0 +1,12 @@
using Ivanov_components.Models;
namespace Ivanov_components.Helpers
{
public interface IContext : ICreator
{
void CreateTable(string[,] data);
void CreateTableWithHeader();
void CreateMultiHeader<T>(TableWithHeaderConfig<T> config);
void LoadDataToTableWithMultiHeader(string[,] data, int rowHeight);
}
}

View File

@@ -0,0 +1,11 @@
using Ivanov_components.Models;
namespace Ivanov_components.Helpers
{
public interface ICreator
{
void CreateHeader(string header);
void SaveDoc(string filepath);
void CreateBarChart(ChartConfig config);
}
}

View File

@@ -0,0 +1,443 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using Ivanov_components.Models;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using DocumentFormat.OpenXml.Drawing;
namespace Ivanov_components.Helpers
{
public class WorkWithExcel : IContext
{
// внутренний счетчик строк для отслеживания позиции текущей строки в Excel.
private uint _index;
// храним данные листа
private SheetData? _sheetData;
// индекс строки, с которой начинается работа в таблице.
private uint _startRowIndex;
// столбцы
private Columns? _columns;
// гистограмма
private DocumentFormat.OpenXml.Drawing.Charts.Chart? _chart;
private SheetData SheetData => _sheetData ??= new SheetData();
private Columns Columns => _columns ??= new Columns();
public void CreateBarChart(ChartConfig config)
{
_chart = ChartGenerator.GenerateBarChart(config);
}
public void CreateMultiHeader<T>(TableWithHeaderConfig<T> config)
{
var counter = 1u;
var num = 2;
if (config.ColumnsRowsWidth != null)
{
// ширина столбцов
foreach (var item in config.ColumnsRowsWidth.Where(x => x.Column > 0))
{
Columns.Append(new Column
{
Min = (UInt32Value)counter,
Max = (UInt32Value)counter,
Width = (DoubleValue)(item.Column * num),
CustomWidth = (BooleanValue)true
});
counter++;
}
// высота строки
counter = _startRowIndex;
num = 5;
// строка уже есть
if ((from r in SheetData.Elements<Row>()
where (uint)r.RowIndex == counter
select r).Any())
{
var row = (from r in SheetData.Elements<Row>()
where (uint)r.RowIndex == counter
select r).First();
row.Height = (DoubleValue)(config.ColumnsRowsWidth[0].Row * num);
row.CustomHeight = (BooleanValue)true;
}
else
{
SheetData.Append(new Row
{
RowIndex = (UInt32Value)counter,
Height = (DoubleValue)(config.ColumnsRowsWidth[0].Row * num),
CustomHeight = (BooleanValue)true
});
}
}
const uint styleIndex = 2u;
// ищем заголовок
if (config.Headers == null) return;
{
// количество заголовков, кроме заголовка в колонке 0
var num3 = config.Headers.Count(x => x.ColumnIndex > 0);
// извлекаем текст заголовка и создаем ячейку в колонке
CreateCell(0, _startRowIndex,
config.Headers.FirstOrDefault<(int, int, string, string)>
(((int ColumnIndex, int RowIndex, string Header, string PropertyName) x)
=> x is { ColumnIndex: 0, RowIndex: 0 }).Item3, styleIndex);
// создаем все остальные заголовки
for (var i = 0; i < num3; i++)
{
CreateCell(i + 1, _startRowIndex, config.Headers.FirstOrDefault<(int, int, string, string)>
(((int ColumnIndex, int RowIndex, string Header, string PropertyName) x)
=> x.ColumnIndex == i + 1 && x.RowIndex == 0).Item3, styleIndex);
}
}
}
private static void GenerateStyle(OpenXmlPartContainer workbookPart)
{
// рабочая книга
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
workbookStylesPart.Stylesheet = new Stylesheet();
// шрифт
var fonts = new DocumentFormat.OpenXml.Spreadsheet.Fonts
{
Count = (UInt32Value)2u,
KnownFonts = BooleanValue.FromBoolean(value: true)
};
// обычный шрифт
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize
{
Val = (DoubleValue)11.0
},
FontName = new FontName
{
Val = (StringValue)"Calibri"
},
FontFamilyNumbering = new FontFamilyNumbering
{
Val = (Int32Value)2
},
FontScheme = new DocumentFormat.OpenXml.Spreadsheet.FontScheme
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
}
});
// полужирный шрифт
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize
{
Val = (DoubleValue)11.0
},
FontName = new FontName
{
Val = (StringValue)"Calibri"
},
FontFamilyNumbering = new FontFamilyNumbering
{
Val = (Int32Value)2
},
FontScheme = new DocumentFormat.OpenXml.Spreadsheet.FontScheme
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
},
Bold = new Bold()
});
workbookStylesPart.Stylesheet.Append(fonts);
// заливка базовая
var fills = new Fills
{
Count = (UInt32Value)1u
};
fills.Append(new DocumentFormat.OpenXml.Spreadsheet.Fill
{
PatternFill = new DocumentFormat.OpenXml.Spreadsheet.PatternFill
{
PatternType = new EnumValue<PatternValues>(PatternValues.None)
}
});
workbookStylesPart.Stylesheet.Append(fills);
// границы
var borders = new Borders
{
Count = (UInt32Value)2u
};
// пустая граница
borders.Append(new Border
{
LeftBorder = new DocumentFormat.OpenXml.Spreadsheet.LeftBorder(),
RightBorder = new DocumentFormat.OpenXml.Spreadsheet.RightBorder(),
TopBorder = new DocumentFormat.OpenXml.Spreadsheet.TopBorder(),
BottomBorder = new DocumentFormat.OpenXml.Spreadsheet.BottomBorder(),
DiagonalBorder = new DiagonalBorder()
});
// тонкая граница
borders.Append(new Border
{
LeftBorder = new DocumentFormat.OpenXml.Spreadsheet.LeftBorder
{
Style = (EnumValue<BorderStyleValues>)BorderStyleValues.Thin
},
RightBorder = new DocumentFormat.OpenXml.Spreadsheet.RightBorder
{
Style = (EnumValue<BorderStyleValues>)BorderStyleValues.Thin
},
TopBorder = new DocumentFormat.OpenXml.Spreadsheet.TopBorder
{
Style = (EnumValue<BorderStyleValues>)BorderStyleValues.Thin
},
BottomBorder = new DocumentFormat.OpenXml.Spreadsheet.BottomBorder
{
Style = (EnumValue<BorderStyleValues>)BorderStyleValues.Thin
}
});
workbookStylesPart.Stylesheet.Append(borders);
// форматы для ячеек
var cellFormats = new CellFormats
{
Count = (UInt32Value)3u
};
// используется обычный шрифт, без границ и заливок.
cellFormats.Append(new CellFormat
{
NumberFormatId = (UInt32Value)0u,
FormatId = (UInt32Value)0u,
FontId = (UInt32Value)0u,
BorderId = (UInt32Value)0u,
FillId = (UInt32Value)0u
});
// тонкая граница
cellFormats.Append(new CellFormat
{
NumberFormatId = (UInt32Value)0u,
FormatId = (UInt32Value)0u,
FontId = (UInt32Value)0u,
BorderId = (UInt32Value)1u,
FillId = (UInt32Value)0u
});
// текст с тонкой границей и полужирным шрифтом
cellFormats.Append(new CellFormat
{
NumberFormatId = (UInt32Value)0u,
FormatId = (UInt32Value)0u,
FontId = (UInt32Value)1u,
BorderId = (UInt32Value)1u,
FillId = (UInt32Value)0u,
Alignment = new Alignment
{
Horizontal = (EnumValue<HorizontalAlignmentValues>)HorizontalAlignmentValues.Center,
Vertical = (EnumValue<VerticalAlignmentValues>)VerticalAlignmentValues.Center,
WrapText = (BooleanValue)true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
public void CreateHeader(string header)
{
// жирный текст в ячейку А1
_index = 1u;
var cell = CreateCell("A", _index);
var run = new DocumentFormat.OpenXml.Spreadsheet.Run();
run.Append(new DocumentFormat.OpenXml.Spreadsheet.Text(header));
run.RunProperties = new DocumentFormat.OpenXml.Spreadsheet.RunProperties(new Bold());
var inlineString = new InlineString();
inlineString.Append(run);
cell.Append(inlineString);
cell.DataType = (EnumValue<CellValues>)CellValues.InlineString;
_index++;
}
// создаем таблицу
public void CreateTable(string[,] data)
{
for (var i = 0; i < data.GetLength(0); i++)
{
for (var j = 0; j < data.GetLength(1); j++)
{
CreateCell(j, (uint)(i + _index), data[i, j], 2u);
}
}
_index += (uint)data.GetLength(0);
}
// создаем ячейки
private Cell CreateCell(string columnName, uint rowIndex)
{
var columnName2 = columnName;
var text = columnName2 + rowIndex;
Row row;
if ((from r in SheetData.Elements<Row>()
where (uint)r.RowIndex == rowIndex
select r).Any())
{
row = (from r in SheetData.Elements<Row>()
where (uint)r.RowIndex == rowIndex
select r).First();
}
else
{
row = new Row
{
RowIndex = (UInt32Value)rowIndex
};
SheetData.Append(row);
}
var cell = row.Elements<Cell>().FirstOrDefault(c => c.CellReference!.Value == columnName2 + rowIndex);
if (cell != null) return cell;
var referenceChild = row.Elements<Cell>()
.FirstOrDefault(
item => item.CellReference!.Value!.Length == text.Length &&
string.Compare(item.CellReference!.Value, text, StringComparison.OrdinalIgnoreCase) > 0);
cell = new Cell
{
CellReference = (StringValue)text
};
row.InsertBefore(cell, referenceChild);
return cell;
}
private static string GetExcelColumnName(int columnNumber)
{
columnNumber++;
var num = columnNumber;
var text = string.Empty;
while (num > 0)
{
var num2 = (num - 1) % 26;
text = Convert.ToChar(65 + num2) + text;
num = (num - num2) / 26;
}
return text;
}
private void CreateCell(int columnIndex, uint rowIndex, string text, uint styleIndex)
{
var cell = CreateCell(GetExcelColumnName(columnIndex), rowIndex);
cell.CellValue = new CellValue(text);
cell.DataType = (EnumValue<CellValues>)CellValues.String;
cell.StyleIndex = (UInt32Value)styleIndex;
}
public void SaveDoc(string filepath)
{
if (string.IsNullOrEmpty(filepath))
{
throw new ArgumentNullException("File name is empty");
}
if (SheetData == null)
{
throw new ArgumentNullException("Dock body is empty! Nothing to save!");
}
using var spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
var workbookPart = spreadsheetDocument.AddWorkbookPart();
GenerateStyle(workbookPart);
workbookPart.Workbook = new Workbook();
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
if (_columns != null)
{
worksheetPart.Worksheet.Append(_columns);
}
worksheetPart.Worksheet.Append(SheetData);
var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
var sheet = new Sheet
{
Id = (StringValue)spreadsheetDocument.WorkbookPart!.GetIdOfPart(worksheetPart),
SheetId = (UInt32Value)1u,
Name = (StringValue)"List 1"
};
sheets.Append(sheet);
if (_chart == null) return;
var drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
worksheetPart.Worksheet.Append(new Drawing
{
Id = (StringValue)worksheetPart.GetIdOfPart(drawingsPart)
});
worksheetPart.Worksheet.Save();
var chartPart = drawingsPart.AddNewPart<ChartPart>();
chartPart.ChartSpace = new ChartSpace();
chartPart.ChartSpace.Append(new EditingLanguage
{
Val = new StringValue("en-US")
});
chartPart.ChartSpace.Append(_chart);
chartPart.ChartSpace.Save();
drawingsPart.WorksheetDrawing = new WorksheetDrawing();
var twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild(new TwoCellAnchor());
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId("2"), new ColumnOffset("581025"), new RowId("2"), new RowOffset("114300")));
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId("17"), new ColumnOffset("276225"), new RowId("32"), new RowOffset("0")));
var graphicFrame = twoCellAnchor.AppendChild(new DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame());
graphicFrame.Macro = (StringValue)"";
graphicFrame.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameProperties(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties
{
Id = new UInt32Value(2u),
Name = (StringValue)"Chart 1"
}, new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties()));
graphicFrame.Append(new Transform(new Offset
{
X = (Int64Value)0L,
Y = (Int64Value)0L
}, new Extents
{
Cx = (Int64Value)0L,
Cy = (Int64Value)0L
}));
graphicFrame.Append(new Graphic(new GraphicData(new ChartReference
{
Id = (StringValue)drawingsPart.GetIdOfPart(chartPart)
})
{
Uri = (StringValue)"http://schemas.openxmlformats.org/drawingml/2006/chart"
}));
twoCellAnchor.Append(new ClientData());
drawingsPart.WorksheetDrawing.Save();
}
public void CreateTableWithHeader()
{
_startRowIndex = _index;
}
public void LoadDataToTableWithMultiHeader(string[,] data, int rowHeight)
{
const int num = 5;
for (var i = 0u; i < data.GetLength(0); i++)
{
if ((from r in SheetData.Elements<Row>()
where (uint)r.RowIndex == i + 1
select r).Any())
{
var row = (from r in SheetData.Elements<Row>()
where (uint)r.RowIndex == i + 1
select r).First();
row.Height = (DoubleValue)(rowHeight * num);
row.CustomHeight = (BooleanValue)true;
}
else
{
SheetData.Append(new Row
{
RowIndex = (UInt32Value)(i + 1),
Height = (DoubleValue)(rowHeight * num),
CustomHeight = (BooleanValue)true
});
}
}
_startRowIndex++;
for (var j = 0; j < data.GetLength(0); j++)
{
for (var k = 0; k < data.GetLength(1); k++)
{
CreateCell(k, _startRowIndex, data[j, k], k == 0 ? 2u : 1u);
}
_startRowIndex++;
}
}
}
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,19 @@
using DocumentFormat.OpenXml.Spreadsheet;
namespace Ivanov_components.Models
{
public class ChartConfig : DocumentConfig
{
public string ChartTitle { get; init; } = string.Empty;
public Location LegendLocation { get; init; }
public Dictionary<string, List<(string Name, double Value)>>? Data { get; init; }
public void CheckFields()
{
if (Data == null || Data.Count == 0)
{
throw new ArgumentNullException("Data count is null");
}
}
}
}

View File

@@ -0,0 +1,8 @@
namespace Ivanov_components.Models
{
public class DocumentConfig
{
public string FilePath { get; init; } = string.Empty;
public string Header { get; init; } = string.Empty;
}
}

View File

@@ -0,0 +1,10 @@
namespace Ivanov_components.Models
{
public enum Location
{
Left,
Right,
Top,
Bottom
}
}

View File

@@ -0,0 +1,15 @@
namespace Ivanov_components.Models
{
public class TableConfig : DocumentConfig
{
public List<string[,]>? Data { get; init; }
public void CheckFields()
{
if (Data == null || Data.Count == 0 || Data.All(x => x.Length == 0))
{
throw new ArgumentNullException("Data is null");
}
}
}
}

View File

@@ -0,0 +1,26 @@
namespace Ivanov_components.Models
{
public class TableWithHeaderConfig<T> : DocumentConfig
{
public (int Columns, int Rows) ColumnsRowsDataCount { get; set; }
public List<(int Column, int Row)>? ColumnsRowsWidth { get; init; }
public List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)>? Headers { get; init; }
public List<T>? Data { get; init; }
public void CheckFields()
{
if (Data == null || Data.Count == 0)
{
throw new ArgumentNullException("No data");
}
if (ColumnsRowsWidth is null || ColumnsRowsWidth.Count == 0)
{
throw new ArgumentNullException("Rows width invalid");
}
if (Headers is null || Headers.Count == 0)
{
throw new ArgumentNullException("Header data invalid");
}
}
}
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ivanov_visual_components
{
public class ColumnsConfiguratoin
{
public int ColumnsCount { get; set; }
public string[] NameColumn { get; set; }
public int[] Width { get; set; }
public bool[] Visible { get; set; }
public string[] PropertiesObject { get; set; }
}
}

View File

@@ -0,0 +1,74 @@
namespace Ivanov_visual_components
{
partial class DateBoxWithNull
{
/// <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()
{
this.CheckBoxNull = new System.Windows.Forms.CheckBox();
this.TextBoxDate = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// CheckBoxNull
//
this.CheckBoxNull.AutoSize = true;
this.CheckBoxNull.Location = new System.Drawing.Point(3, 7);
this.CheckBoxNull.Name = "CheckBoxNull";
this.CheckBoxNull.Size = new System.Drawing.Size(15, 14);
this.CheckBoxNull.TabIndex = 0;
this.CheckBoxNull.UseVisualStyleBackColor = true;
this.CheckBoxNull.CheckedChanged += new System.EventHandler(this.CheckBoxNull_CheckedChanged);
//
// TextBoxDate
//
this.TextBoxDate.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.TextBoxDate.Location = new System.Drawing.Point(24, 3);
this.TextBoxDate.Name = "TextBoxDate";
this.TextBoxDate.Size = new System.Drawing.Size(271, 23);
this.TextBoxDate.TabIndex = 1;
this.TextBoxDate.TextChanged += new System.EventHandler(this.TextBoxDate_TextChanged);
//
// DateBoxWithNull
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ControlLight;
this.Controls.Add(this.TextBoxDate);
this.Controls.Add(this.CheckBoxNull);
this.Name = "DateBoxWithNull";
this.Size = new System.Drawing.Size(298, 29);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private CheckBox CheckBoxNull;
private TextBox TextBoxDate;
}
}

View File

@@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace Ivanov_visual_components
{
public partial class DateBoxWithNull : UserControl
{
public EventHandler? _changeEvent;
public EventHandler? _checkBoxEvent;
public Exception? Error;
public DateBoxWithNull()
{
InitializeComponent();
}
public DateTime? Value
{
get
{
Error = null;
if (!CheckBoxNull.Checked)
{
if (string.IsNullOrEmpty(TextBoxDate.Text))
{
Error = new NotFilledException("Text box can't be empty, click checkbox if value must be empty!");
return null;
}
if (DateTime.TryParseExact(TextBoxDate.Text, "dd/MM/yyyy", null, DateTimeStyles.None, out DateTime parsedDate))
{
return parsedDate;
}
else
{
Error = new ParseException($"Wrong format <{TextBoxDate.Text}>!");
return null;
}
}
return null;
}
set
{
if (value is null)
{
CheckBoxNull.Checked = true;
}
else
{
TextBoxDate.Text = value?.ToString("dd/MM/yyyy");
CheckBoxNull.Checked = false;
}
}
}
public event EventHandler CheckBoxEvent
{
add { _checkBoxEvent += value; }
remove { _checkBoxEvent += value; }
}
public event EventHandler ChangeEvent
{
add { _changeEvent += value; }
remove { _changeEvent += value; }
}
private void TextBoxDate_TextChanged(object sender, EventArgs e)
{
_changeEvent?.Invoke(sender, e);
}
private void CheckBoxNull_CheckedChanged(object sender, EventArgs e)
{
TextBoxDate.Enabled = !CheckBoxNull.Checked;
_checkBoxEvent?.Invoke(sender, e);
}
}
}

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,62 @@
namespace Ivanov_visual_components
{
partial class ItemList
{
/// <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()
{
this.ListBoxCustom = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// ListBoxCustom
//
this.ListBoxCustom.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ListBoxCustom.FormattingEnabled = true;
this.ListBoxCustom.ItemHeight = 15;
this.ListBoxCustom.Location = new System.Drawing.Point(0, 0);
this.ListBoxCustom.Name = "ListBoxCustom";
this.ListBoxCustom.Size = new System.Drawing.Size(272, 259);
this.ListBoxCustom.TabIndex = 0;
this.ListBoxCustom.SelectedIndexChanged += new System.EventHandler(this.ListBoxCustom_SelectedIndexChanged);
//
// ItemList
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.ListBoxCustom);
this.Name = "ItemList";
this.Size = new System.Drawing.Size(272, 265);
this.ResumeLayout(false);
}
#endregion
private ListBox ListBoxCustom;
}
}

View File

@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Ivanov_visual_components
{
public partial class ItemList : UserControl
{
private EventHandler? _changeEvent;
public ListBox.ObjectCollection Items => ListBoxCustom.Items;
public ItemList()
{
InitializeComponent();
}
public void Clear()
{
ListBoxCustom.Items.Clear();
}
public event EventHandler ChangeEvent
{
add
{
_changeEvent += value;
}
remove
{
_changeEvent -= value;
}
}
public string? SelectedElement
{
get
{
return (ListBoxCustom.SelectedIndex != -1 && ListBoxCustom.SelectedItem != null)
? ListBoxCustom.SelectedItem.ToString()
: string.Empty;
}
set
{
if (!string.IsNullOrEmpty(value))
{
int index = ListBoxCustom.FindString(value);
if (index == -1) return;
ListBoxCustom.SetSelected(index, true);
}
}
}
private void ListBoxCustom_SelectedIndexChanged(object sender, EventArgs e)
{
_changeEvent?.Invoke(sender, e);
}
}
}

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,72 @@
namespace Ivanov_visual_components
{
partial class ItemTable
{
/// <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()
{
this.DataGridViewItems = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.DataGridViewItems)).BeginInit();
this.SuspendLayout();
//
// DataGridViewItems
//
this.DataGridViewItems.AllowUserToAddRows = false;
this.DataGridViewItems.AllowUserToDeleteRows = false;
this.DataGridViewItems.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.DataGridViewItems.BackgroundColor = System.Drawing.SystemColors.ButtonFace;
this.DataGridViewItems.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.DataGridViewItems.GridColor = System.Drawing.SystemColors.ActiveCaptionText;
this.DataGridViewItems.Location = new System.Drawing.Point(0, 0);
this.DataGridViewItems.MultiSelect = false;
this.DataGridViewItems.Name = "DataGridViewItems";
this.DataGridViewItems.ReadOnly = true;
this.DataGridViewItems.RowHeadersVisible = false;
this.DataGridViewItems.RowTemplate.Height = 25;
this.DataGridViewItems.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.DataGridViewItems.ShowEditingIcon = false;
this.DataGridViewItems.Size = new System.Drawing.Size(548, 358);
this.DataGridViewItems.TabIndex = 0;
//
// ItemTable
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.DataGridViewItems);
this.Name = "ItemTable";
this.Size = new System.Drawing.Size(548, 358);
((System.ComponentModel.ISupportInitialize)(this.DataGridViewItems)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView DataGridViewItems;
}
}

View File

@@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Ivanov_visual_components
{
public partial class ItemTable : UserControl
{
public ItemTable()
{
InitializeComponent();
}
public int SelectedRow
{
get
{
return DataGridViewItems.SelectedRows[0].Index;
}
set
{
if (DataGridViewItems.SelectedRows.Count <= value || value < 0)
{
throw new ArgumentException(string.Format("{0} is an invalid row index.", value));
}
else
{
DataGridViewItems.ClearSelection();
DataGridViewItems.Rows[value].Selected = true;
}
}
}
public void ClearDataGrid()
{
DataGridViewItems.DataSource = null;
DataGridViewItems.Rows.Clear();
}
public void ConfigColumn(ColumnsConfiguratoin columnsData)
{
DataGridViewItems.ColumnCount = columnsData.ColumnsCount;
for (int i = 0; i < columnsData.ColumnsCount; i++)
{
DataGridViewItems.Columns[i].Name = columnsData.NameColumn[i];
DataGridViewItems.Columns[i].Width = columnsData.Width[i];
DataGridViewItems.Columns[i].Visible = columnsData.Visible[i];
DataGridViewItems.Columns[i].DataPropertyName = columnsData.PropertiesObject[i];
}
}
public T GetSelectedObjectInRow<T>() where T : class, new()
{
T val = new();
var propertiesObj = typeof(T).GetProperties();
foreach (var properties in propertiesObj)
{
bool propIsExist = false;
int columnIndex = 0;
for (; columnIndex < DataGridViewItems.Columns.Count; columnIndex++)
{
if (DataGridViewItems.Columns[columnIndex].DataPropertyName.ToString() == properties.Name)
{
propIsExist = true;
break;
}
}
if (propIsExist)
{
object value = DataGridViewItems.SelectedRows[0].Cells[columnIndex].Value;
properties.SetValue(val, Convert.ChangeType(value, properties?.PropertyType));
};
}
return val;
}
public void AddItem<T>(T item, int RowIndex, int ColumnIndex)
{
if (item == null)
{
return;
}
string propertyName = DataGridViewItems.Columns[ColumnIndex].DataPropertyName.ToString();
string? value = item.GetType().GetProperty(propertyName)?.GetValue(item)?.ToString();
if (RowIndex >= DataGridViewItems.Rows.Count)
{
DataGridViewItems.RowCount = RowIndex + 1;
}
DataGridViewItems.Rows[RowIndex].Cells[ColumnIndex].Value = value;
}
}
}

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ivanov_visual_components
{
public class NotFilledException : Exception
{
public NotFilledException() { }
public NotFilledException(string message) : base(message) { }
public NotFilledException(string message, Exception inner) : base(message, inner) { }
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ivanov_visual_components
{
public class ParseException : Exception
{
public ParseException() { }
public ParseException(string message) : base(message) { }
public ParseException(string message, Exception innerException) : base(message, innerException) { }
}
}

37
KOP/KOP.sln Normal file
View File

@@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.35122.118
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ivanov_visual_components", "Ivanov_visual_components\Ivanov_visual_components.csproj", "{3FEAB427-D75C-442E-B5FE-6285202B442C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ivanov_App", "Ivanov_App\Ivanov_App.csproj", "{64CD7137-E0BF-4F35-8F33-B07AFED1393F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ivanov_components", "Ivanov_components\Ivanov_components.csproj", "{E162208D-662D-4419-9B33-A61189E0CC20}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3FEAB427-D75C-442E-B5FE-6285202B442C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3FEAB427-D75C-442E-B5FE-6285202B442C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3FEAB427-D75C-442E-B5FE-6285202B442C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3FEAB427-D75C-442E-B5FE-6285202B442C}.Release|Any CPU.Build.0 = Release|Any CPU
{64CD7137-E0BF-4F35-8F33-B07AFED1393F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{64CD7137-E0BF-4F35-8F33-B07AFED1393F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{64CD7137-E0BF-4F35-8F33-B07AFED1393F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{64CD7137-E0BF-4F35-8F33-B07AFED1393F}.Release|Any CPU.Build.0 = Release|Any CPU
{E162208D-662D-4419-9B33-A61189E0CC20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E162208D-662D-4419-9B33-A61189E0CC20}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E162208D-662D-4419-9B33-A61189E0CC20}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E162208D-662D-4419-9B33-A61189E0CC20}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1A537B19-2DD7-4FCC-9CFD-9A7FAEE5D675}
EndGlobalSection
EndGlobal