Compare commits

...

8 Commits
main ... lab2

Author SHA1 Message Date
c471b98fc7 edit lab2 2024-10-29 09:50:23 +03:00
revengel66
d0c502a619 lab2 ready 2024-10-28 21:49:23 +04:00
revengel66
0880abd42e ready component 2 2024-10-28 20:46:47 +04:00
revengel66
19b9d83d74 lab 2 in process 2024-10-28 20:23:38 +04:00
e6dd043cbb lab 2 in process 2024-10-15 10:27:49 +03:00
6190df5e28 commit 2024-10-10 17:03:54 +03:00
revengel66
12c7f4caff commit try create table 2024-09-30 23:54:03 +04:00
revengel66
cc45235f69 in process 2024-09-30 22:43:40 +04:00
25 changed files with 1359 additions and 0 deletions

31
ComponentsLab.sln Normal file
View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34723.18
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComponentsLibrary", "ComponentsLibrary\ComponentsLibrary.csproj", "{62BF8781-DBD1-4FC8-BE56-FDF96F51937D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComponentsView", "ComponentsView\ComponentsView.csproj", "{3ABCBF18-4F14-44A4-B921-329CFCE9E5DF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{62BF8781-DBD1-4FC8-BE56-FDF96F51937D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{62BF8781-DBD1-4FC8-BE56-FDF96F51937D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{62BF8781-DBD1-4FC8-BE56-FDF96F51937D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{62BF8781-DBD1-4FC8-BE56-FDF96F51937D}.Release|Any CPU.Build.0 = Release|Any CPU
{3ABCBF18-4F14-44A4-B921-329CFCE9E5DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3ABCBF18-4F14-44A4-B921-329CFCE9E5DF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3ABCBF18-4F14-44A4-B921-329CFCE9E5DF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3ABCBF18-4F14-44A4-B921-329CFCE9E5DF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {402122A1-1FB6-406E-869E-FADF8DF1F7EA}
EndGlobalSection
EndGlobal

31
ComponentsLibrary.sln Normal file
View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34723.18
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComponentsLibrary", "ComponentsLibrary\ComponentsLibrary.csproj", "{405DC0B1-6F7C-462D-A8F0-435EE9A1983B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComponentsView", "ComponentsView\ComponentsView.csproj", "{92F249DD-167B-42EB-98A1-9B4B71D69B61}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{405DC0B1-6F7C-462D-A8F0-435EE9A1983B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{405DC0B1-6F7C-462D-A8F0-435EE9A1983B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{405DC0B1-6F7C-462D-A8F0-435EE9A1983B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{405DC0B1-6F7C-462D-A8F0-435EE9A1983B}.Release|Any CPU.Build.0 = Release|Any CPU
{92F249DD-167B-42EB-98A1-9B4B71D69B61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{92F249DD-167B-42EB-98A1-9B4B71D69B61}.Debug|Any CPU.Build.0 = Debug|Any CPU
{92F249DD-167B-42EB-98A1-9B4B71D69B61}.Release|Any CPU.ActiveCfg = Release|Any CPU
{92F249DD-167B-42EB-98A1-9B4B71D69B61}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6D17BCB4-04C0-4B95-B46C-535B01552FDD}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,36 @@
namespace ComponentsLibrary
{
partial class ComponentBigText
{
/// <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,87 @@
using ComponentsLibrary.entities;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.ComponentModel;
namespace ComponentsLibrary
{
public partial class ComponentBigText : Component
{
public ComponentBigText()
{
InitializeComponent();
}
public ComponentBigText(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateWordText(DocumentSymple docInfo)
{
if (string.IsNullOrEmpty(docInfo.FileUrl) || string.IsNullOrEmpty(docInfo.Title) || !CheckData(docInfo.Text))
{
throw new Exception("Не все данные заполнены");
}
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(docInfo.FileUrl, WordprocessingDocumentType.Document))
{
// Добавляем главную часть документа
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
// Создаем параграф для заголовка
Paragraph titleParagraph = new Paragraph();
// Задаем свойства параграфа (центровка и отступ)
ParagraphProperties paragraphProperties = new ParagraphProperties();
paragraphProperties.AppendChild(new Justification() { Val = JustificationValues.Center });
// Применяем свойства параграфа к заголовку
titleParagraph.AppendChild(paragraphProperties);
// Создаем "бегунок" текста
Run titleRun = new Run();
// Устанавливаем свойства "бегунка" (шрифт, размер, жирный шрифт)
RunProperties runProperties = new RunProperties();
runProperties.AppendChild(new Bold());
runProperties.AppendChild(new FontSize() { Val = "48" }); // Размер шрифта, 24pt
// Применяем свойства к тексту
titleRun.AppendChild(runProperties);
// Добавляем текст заголовка
titleRun.AppendChild(new Text(docInfo.Title));
// Добавляем "бегунок" с текстом в параграф
titleParagraph.AppendChild(titleRun);
// Добавляем параграф в тело документа
body.AppendChild(titleParagraph);
foreach (var line in docInfo.Text)
{
Paragraph paragraph = new Paragraph(new Run(new Text(line)));
body.Append(paragraph);
}
mainPart.Document.Save();
}
}
bool CheckData(string[] data)
{
for (int i = 0; i < data.Length; i++)
{
if (string.IsNullOrEmpty(data[i])) return false;
}
return true;
}
}
}

View File

@ -0,0 +1,36 @@
namespace ComponentsLibrary
{
partial class ComponentDiagram
{
/// <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,100 @@
using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Drawing.Charts;
using ComponentsLibrary.entities;
using System.ComponentModel;
namespace ComponentsLibrary
{
public partial class ComponentDiagram : Component
{
public ComponentDiagram()
{
InitializeComponent();
}
public ComponentDiagram(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void AddDiagram(DocumentDiagram diagramInfo)
{
if (!CheckData(diagramInfo.DataList))
{
throw new Exception("Не заполнены данные");
}
//Создание документа и настройка шрифта
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Aspose.Words.Font font = builder.Font;
font.Size = 24;
font.Bold = true;
font.Color = Color.Black;
font.Name = "Calibri";
//Настройка форматирования параграфа
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.SpaceAfter = 24;
paragraphFormat.Alignment = ParagraphAlignment.Center;
paragraphFormat.KeepTogether = true;
//Добавление заголовка
builder.Writeln(diagramInfo.FileHeader);
//Создание диаграммы
Shape shape = builder.InsertChart(ChartType.Line, 500, 270);
Chart chart = shape.Chart;
chart.Title.Text = diagramInfo.DiagramName; //Настройка заголовка диаграммы
ChartSeriesCollection seriesColl = chart.Series;
seriesColl.Clear();
string[] cats; //x - категории
double[] doubs; //y - данные
//Добавление серий данных
foreach (var data in diagramInfo.DataList)
{
cats = new string[diagramInfo.DataList.Count];
doubs = new double[diagramInfo.DataList.Count];
int i = 0;
foreach (var (name, value) in data.LineData)
{
cats[i] = name;
doubs[i] = value;
i++;
}
seriesColl.Add(data.LineName, cats, doubs);
}
//Настройка легенды
ChartLegend legend = chart.Legend;
legend.Position = (LegendPosition)diagramInfo.AreaLegend;
legend.Overlay = true;
doc.Save(diagramInfo.FileUrl);
}
static bool CheckData(List<DataLine> data)
{
string[] cats = new string[data.Count];
double[] doubs = new double[data.Count];
foreach (var _data in data)
{
int i = 0;
foreach (var (name, value) in _data.LineData)
{
cats[i] = name;
doubs[i] = value;
i++;
}
if (string.IsNullOrEmpty(_data.LineName) || cats.Length == 0 || doubs.Length == 0)
return false;
}
return true;
}
}
}

View File

@ -0,0 +1,36 @@
namespace ComponentsLibrary
{
partial class ComponentTable
{
/// <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,147 @@
using Aspose.Words;
using Aspose.Words.Tables;
using ComponentsLibrary.entities;
using System.ComponentModel;
namespace ComponentsLibrary
{
public partial class ComponentTable : Component
{
public ComponentTable()
{
InitializeComponent();
}
public ComponentTable(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateTable<T>(DocumentTable<T> tableWord) where T : class
{
// Проверка наличия данных и определений столбцов
if (tableWord.Items == null || tableWord.Items.Count == 0 || tableWord.ColumnParameters == null || tableWord.ColumnParameters.Count == 0)
{
throw new ArgumentException("Не все данные заполнены");
}
// Проверка, что все ячейки шапки заполнены и для каждого столбца определено свойство/поле класса
foreach (var columnParameters in tableWord.ColumnParameters)
{
if (string.IsNullOrEmpty(columnParameters.PropertyName))
{
throw new ArgumentException($"Incomplete column definition: {columnParameters.FirstRowHeader}");
}
}
// Создание документа
Document document = new Document();
DocumentBuilder builder = new DocumentBuilder(document);
// Установка стиля заголовка
Style titleStyle = builder.Document.Styles.Add(StyleType.Paragraph, "Title");
titleStyle.Font.Size = 16;
titleStyle.Font.Bold = true;
// Установка заголовка документа
builder.ParagraphFormat.Style = titleStyle;
builder.Writeln(tableWord.Title);
// Создание таблицы
Table table = builder.StartTable();
// Установка стиля для шапки таблицы
Style headerStyle = builder.Document.Styles.Add(StyleType.Paragraph, "HeaderStyle");
headerStyle.Font.Size = 14;
headerStyle.Font.Bold = true;
// Создание первой строки (шапка)
foreach (var columnParameters in tableWord.ColumnParameters)
{
builder.InsertCell();
builder.ParagraphFormat.Style = headerStyle;
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(columnParameters.Width);
builder.Write(columnParameters.FirstRowHeader);
}
builder.EndRow();
// Создание второй строки (шапка)
foreach (var columnParameters in tableWord.ColumnParameters)
{
builder.InsertCell();
builder.ParagraphFormat.Style = headerStyle;
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(columnParameters.Width);
builder.Write(columnParameters.SecondRowHeader);
}
builder.EndRow();
int startCellIndex = -1;
int endCellIndex = -1;
// Создаем набор для хранения индексов ячеек, которые уже объединены по горизонтали
HashSet<int> horizontallyMergedCells = new();
// Объединение ячеек в первой строке шапки таблицы (если необходимо)
foreach (var mergedColumn in tableWord.MergedColumns)
{
startCellIndex = mergedColumn[0];
endCellIndex = mergedColumn[^1];
for (int i = startCellIndex; i <= endCellIndex; i++)
{
// Устанавливаем горизонтальное объединение
table.Rows[0].Cells[i].CellFormat.HorizontalMerge = i == startCellIndex ? CellMerge.First : CellMerge.Previous;
horizontallyMergedCells.Add(i); // Сохраняем индекс ячейки, которая объединена по горизонтали
// Устанавливаем выравнивание по центру
if (i == startCellIndex)
{
// Центрируем текст внутри ячейки
table.Rows[0].Cells[i].Paragraphs[0].ParagraphFormat.Alignment = ParagraphAlignment.Center;
}
}
}
// Установка вертикального объединения заголовков
for (int columnIndex = 0; columnIndex < tableWord.ColumnParameters.Count; columnIndex++)
{
// Пропускаем столбцы, которые уже объединены по горизонтали
if (horizontallyMergedCells.Contains(columnIndex))
continue;
table.Rows[0].Cells[columnIndex].CellFormat.VerticalMerge = CellMerge.First;
table.Rows[1].Cells[columnIndex].CellFormat.VerticalMerge = CellMerge.Previous;
table.Rows[0].Cells[columnIndex].CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
table.Rows[1].Cells[columnIndex].CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
}
// Установка стиля для данных таблицы
Style dataStyle = builder.Document.Styles.Add(StyleType.Paragraph, "DataStyle");
dataStyle.Font.Size = 12;
dataStyle.Font.Bold = false;
// Вставка данных в таблицу
foreach (var item in tableWord.Items)
{
foreach (var сolumnParameters in tableWord.ColumnParameters)
{
builder.InsertCell();
builder.ParagraphFormat.Style = dataStyle;
// Получение значения свойства/поля объекта по заданному имени
var propertyValue = item.GetType().GetProperty(сolumnParameters.PropertyName)?.GetValue(item)?.ToString();
builder.Write(propertyValue ?? string.Empty);
}
builder.EndRow();
}
builder.EndTable();
// Сохранение документа в файл
document.Save(tableWord.FileUrl);
}
}
}

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="3.1.0" />
</ItemGroup>
</Project>

View File

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

View File

@ -0,0 +1,36 @@
namespace ComponentsLibrary
{
partial class TestComponent
{
/// <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,61 @@
using System.ComponentModel;
using static System.Net.Mime.MediaTypeNames;
namespace ComponentsLibrary
{
public partial class TestComponent : Component
{
private string _fileName;
//DocumentEntry doc = new DocumentEntry("C:\\Users\\Natalia\\Desktop\\5semestr\\KOP\\KOP-PIbd-32-Katysheva-N-E", "doc.docx", text);
public string FileName
{
set
{
if (string.IsNullOrEmpty(value))
{
return;
}
if (!value.EndsWith(".txt"))
{
throw new ArgumentException("No txt file");
}
_fileName = value;
}
}
public TestComponent()
{
InitializeComponent();
_fileName = string.Empty;
}
public TestComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
_fileName = string.Empty;
}
public bool SaveToFile(string[] texts)
{
CheckFileExsists();
using var writer = new StreamWriter(_fileName, true);
foreach (var text in texts)
{
writer.WriteLine(text);
}
writer.Flush();
return true;
}
private void CheckFileExsists()
{
if (string.IsNullOrEmpty(_fileName))
{
throw new ArgumentNullException(_fileName);
}
if (!File.Exists(_fileName))
{
File.Create(_fileName).Dispose();
}
}
}
}

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 @@
namespace ComponentsLibrary.entities
{
public class ColumnParams
{
public string FirstRowHeader { get; set; } = string.Empty;
public string SecondRowHeader { get; set; } = string.Empty;
public string PropertyName { get; set; } = string.Empty;
public double Width { get; set; }
}
}

View File

@ -0,0 +1,15 @@
namespace ComponentsLibrary.entities
{
public class DataLine
{
public string LineName { get; set; } = string.Empty;
public (string, double)[] LineData { get; set; }
public DataLine(string nameSeries, (string, double)[] lineData)
{
LineName = nameSeries;
LineData = lineData;
}
}
}

View File

@ -0,0 +1,32 @@
using ComponentsLibrary.entities.enums;
using DocumentFormat.OpenXml.Drawing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComponentsLibrary.entities
{
public class DocumentDiagram
{
public string FileUrl = string.Empty;
public string FileHeader = string.Empty;
public string DiagramName = string.Empty;
public EnumAreaLegend AreaLegend;
public List<DataLine> DataList = new();
public DocumentDiagram(string fileUrl, string fileHeader, string diagramName, EnumAreaLegend areaLegend, List<DataLine> dataList)
{
FileUrl = fileUrl;
FileHeader = fileHeader;
DiagramName = diagramName;
AreaLegend = areaLegend;
DataList = dataList;
}
}
}

View File

@ -0,0 +1,16 @@
namespace ComponentsLibrary.entities
{
public class DocumentSymple
{
public string FileUrl { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string[] Text { get; set; }
public DocumentSymple(string fileUrl, string title, string[] text)
{
FileUrl = fileUrl;
Title = title;
Text = text;
}
}
}

View File

@ -0,0 +1,27 @@
namespace ComponentsLibrary.entities
{
public class DocumentTable<T>
{
//путь до файла
public string FileUrl { get; set; } = string.Empty;
//заголовок в документе
public string Title { get; set; } = string.Empty;
//параметры колонок (ширина и тд)
public List<ColumnParams> ColumnParameters { get; set; } = new();
//данные для таблицы
public List<T> Items { get; set; } = new();
//информация по объединению колонок
public List<int[]> MergedColumns { get; set; } = new();
public DocumentTable(string fileUrl, string title, List<ColumnParams> columnParameters, List<T> data, List<int[]> mergedColumns)
{
FileUrl = fileUrl;
Title = title;
ColumnParameters = columnParameters;
Items = data;
MergedColumns = mergedColumns;
}
}
}

View File

@ -0,0 +1,37 @@
namespace ComponentsLibrary.entities
{
public class Employee
{
public string Status { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Age { get; set; }
public string Childrens { get; set; }
public string Car { get; set; }
public string Post { get; set; }
public string Experience { get; set; }
public string Prize { get; set; }
public Employee(string status, string name, string surname, string age,string childrens,string car,string post,string experience,string prize)
{
Status = status;
Name = name;
Surname = surname;
Age = age;
Childrens = childrens;
Car = car;
Post = post;
Experience = experience;
Prize = prize;
}
public Employee() { }
public override string ToString()
{
string temp = Status + ", " + Name + ", " + Surname + ", " + Age + ", " + Childrens + ", " + Car + ", " + Post + ", " + Experience + ", " + Prize;
return temp;
}
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComponentsLibrary.entities.enums
{
public enum EnumAreaLegend
{
None,
Left,
Top,
Right,
Bottom,
TopRight
}
}

View File

@ -0,0 +1,15 @@
<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="..\ComponentsLibrary\ComponentsLibrary.csproj" />
</ItemGroup>
</Project>

129
ComponentsView/FormComponents.Designer.cs generated Normal file
View File

@ -0,0 +1,129 @@
namespace ComponentsView
{
partial class FormComponents
{
/// <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()
{
components = new System.ComponentModel.Container();
testComponent = new ComponentsLibrary.TestComponent(components);
richTextBoxTest = new RichTextBox();
buttonSaveText = new Button();
componentBigText = new ComponentsLibrary.ComponentBigText(components);
richTextBoxWord = new RichTextBox();
buttonSaveTextWord = new Button();
componentTable = new ComponentsLibrary.ComponentTable(components);
buttonSaveTable = new Button();
buttonSaveDiagram = new Button();
componentDiagram = new ComponentsLibrary.ComponentDiagram(components);
SuspendLayout();
//
// richTextBoxTest
//
richTextBoxTest.Location = new Point(12, 12);
richTextBoxTest.Name = "richTextBoxTest";
richTextBoxTest.Size = new Size(175, 96);
richTextBoxTest.TabIndex = 0;
richTextBoxTest.Text = "";
//
// buttonSaveText
//
buttonSaveText.Location = new Point(12, 114);
buttonSaveText.Name = "buttonSaveText";
buttonSaveText.Size = new Size(175, 23);
buttonSaveText.TabIndex = 1;
buttonSaveText.Text = "Загрузить в txt";
buttonSaveText.UseVisualStyleBackColor = true;
buttonSaveText.Click += buttonSaveText_Click;
//
// richTextBoxWord
//
richTextBoxWord.Location = new Point(193, 12);
richTextBoxWord.Name = "richTextBoxWord";
richTextBoxWord.Size = new Size(169, 96);
richTextBoxWord.TabIndex = 2;
richTextBoxWord.Text = "";
//
// buttonSaveTextWord
//
buttonSaveTextWord.Location = new Point(193, 114);
buttonSaveTextWord.Name = "buttonSaveTextWord";
buttonSaveTextWord.Size = new Size(169, 23);
buttonSaveTextWord.TabIndex = 3;
buttonSaveTextWord.Text = "Сохранить в word";
buttonSaveTextWord.UseVisualStyleBackColor = true;
buttonSaveTextWord.Click += buttonSaveTextWord_Click;
//
// buttonSaveTable
//
buttonSaveTable.Location = new Point(12, 143);
buttonSaveTable.Name = "buttonSaveTable";
buttonSaveTable.Size = new Size(350, 41);
buttonSaveTable.TabIndex = 5;
buttonSaveTable.Text = "Cоздать документ с таблицей";
buttonSaveTable.UseVisualStyleBackColor = true;
buttonSaveTable.Click += buttonSaveTable_Click;
//
// buttonSaveDiagram
//
buttonSaveDiagram.Location = new Point(12, 190);
buttonSaveDiagram.Name = "buttonSaveDiagram";
buttonSaveDiagram.Size = new Size(350, 41);
buttonSaveDiagram.TabIndex = 6;
buttonSaveDiagram.Text = "Cоздать документ с диаграмой";
buttonSaveDiagram.UseVisualStyleBackColor = true;
buttonSaveDiagram.Click += buttonSaveDiagram_Click;
//
// FormComponents
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(373, 244);
Controls.Add(buttonSaveDiagram);
Controls.Add(buttonSaveTable);
Controls.Add(buttonSaveTextWord);
Controls.Add(richTextBoxWord);
Controls.Add(buttonSaveText);
Controls.Add(richTextBoxTest);
Name = "FormComponents";
Text = "Form1";
ResumeLayout(false);
}
#endregion
private ComponentsLibrary.TestComponent testComponent;
private RichTextBox richTextBoxTest;
private Button buttonSaveText;
private ComponentsLibrary.ComponentBigText componentBigText;
private RichTextBox richTextBoxWord;
private Button buttonSaveTextWord;
private ComponentsLibrary.ComponentTable componentTable;
private Button buttonSaveTable;
private Button buttonSaveDiagram;
private ComponentsLibrary.ComponentDiagram componentDiagram;
}
}

View File

@ -0,0 +1,153 @@
using ComponentsLibrary.entities;
using ComponentsLibrary.entities.enums;
using DocumentFormat.OpenXml.Drawing;
namespace ComponentsView
{
public partial class FormComponents : Form
{
public FormComponents()
{
InitializeComponent();
testComponent.FileName = "2.txt";
}
private void buttonSaveText_Click(object sender, EventArgs e)
{
try
{
testComponent.SaveToFile(richTextBoxTest.Lines);
MessageBox.Show("Ñîõàðíåíî óñïåøíî", "Ðåçóëüòàò",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSaveTextWord_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog
{
Filter = "docx|*.docx"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
DocumentSymple doc = new(dialog.FileName, "Ïåðâûé êîìïîíåíò", richTextBoxWord.Lines);
componentBigText.CreateWordText(doc);
MessageBox.Show("Ñîõàðíåíî óñïåøíî", "Ðåçóëüòàò",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonSaveTable_Click(object sender, EventArgs e)
{
List<int[]> mergedColumns = new()
{
new int[] { 1, 5 },
new int[] { 6, 7 },
};
var columns = new List<ColumnParams>
{
new() { FirstRowHeader = "Ñòàòóñ", SecondRowHeader = "", PropertyName = "Status", Width = 1 },
new() { FirstRowHeader = "Ëè÷íûå äàííûå", SecondRowHeader = "Èìÿ",PropertyName = "Name", Width = 1 },
new() { FirstRowHeader = "Ëè÷íûå äàííûå", SecondRowHeader = "Ôàìèëèÿ", PropertyName = "Surname", Width = 1 },
new() { FirstRowHeader = "Ëè÷íûå äàííûå", SecondRowHeader = "Âîçðàñò", PropertyName = "Age", Width = 0.1 },
new() { FirstRowHeader = "Ëè÷íûå äàííûå", SecondRowHeader = "Äåòè", PropertyName = "Childrens", Width = 0.1 },
new() { FirstRowHeader = "Ëè÷íûå äàííûå", SecondRowHeader = "Ìàøèíà", PropertyName = "Car", Width = 1 },
new() { FirstRowHeader = "Ðàáîòà", SecondRowHeader = "Äîëæíîñòü", PropertyName = "Post", Width = 1 },
new() { FirstRowHeader = "Ðàáîòà", SecondRowHeader = "Ñòàæ", PropertyName = "Experience", Width = 1 },
new() { FirstRowHeader = "Ïðåìèÿ", SecondRowHeader = "", PropertyName = "Prize", Width = 1 },
};
var employees = new List<Employee>
{
new() { Status = "Active", Name = "John", Surname = "Doe", Age = "35", Childrens = "2", Car = "Toyota", Post = "Manager", Experience = "10 years", Prize = "5000" },
new() { Status = "On Leave", Name = "Alice", Surname = "Smith", Age = "28", Childrens = "1", Car = "Honda", Post = "Developer", Experience = "5 years", Prize = "3000" },
new() { Status = "Active", Name = "Bob", Surname = "Brown", Age = "40", Childrens = "3", Car = "Ford", Post = "Team Lead", Experience = "15 years", Prize = "7000" },
new() { Status = "Retired", Name = "Carol", Surname = "Johnson", Age = "65", Childrens = "4", Car = "None", Post = "Accountant", Experience = "30 years", Prize = "10000" },
new() { Status = "Active", Name = "David", Surname = "Wilson", Age = "45", Childrens = "2", Car = "Chevrolet", Post = "Designer", Experience = "20 years", Prize = "4000" },
new() { Status = "Active", Name = "Eve", Surname = "Davis", Age = "32", Childrens = "0", Car = "Tesla", Post = "Data Scientist", Experience = "8 years", Prize = "6000" },
new() { Status = "On Leave", Name = "Frank", Surname = "Miller", Age = "38", Childrens = "2", Car = "BMW", Post = "Product Manager", Experience = "12 years", Prize = "5500" },
new() { Status = "Active", Name = "Grace", Surname = "Taylor", Age = "29", Childrens = "1", Car = "Mercedes", Post = "QA Engineer", Experience = "6 years", Prize = "3500" },
new() { Status = "Resigned", Name = "Henry", Surname = "Anderson", Age = "50", Childrens = "3", Car = "Audi", Post = "CTO", Experience = "25 years", Prize = "12000" },
new() { Status = "Active", Name = "Ivy", Surname = "Thomas", Age = "27", Childrens = "0", Car = "Volkswagen", Post = "Intern", Experience = "1 year", Prize = "1000" }
};
using var dialog = new SaveFileDialog
{
Filter = "docx|*.docx"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
DocumentTable<Employee> info = new(dialog.FileName, "Âòîðîé êîìïîíåíò", columns, employees, mergedColumns);
componentTable.CreateTable(info);
MessageBox.Show("Ñîõðàíåíî óñïåøíî", "Ðåçóëüòàò",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonSaveDiagram_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog
{
Filter = "docx|*.docx"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
(string, double)[] series1 = { ("Êàòåãîðèÿ 1", 100), ("Êàòåãîðèÿ 2", 300), ("Êàòåãîðèÿ 3", 400) };
(string, double)[] series2 = { ("Êàòåãîðèÿ 1", 400), ("Êàòåãîðèÿ 2", 300), ("Êàòåãîðèÿ 3", 100) };
(string, double)[] series3 = { ("Êàòåãîðèÿ 1", 200), ("Êàòåãîðèÿ 2", 500), ("Êàòåãîðèÿ 3", 900) };
string fileUrl = dialog.FileName;
string docHeader = "Òðåòèé êîìïîíåíò";
string diagramName = "Ëèíåéíàÿ äèàãðàìà";
List<DataLine> dataList = new List<DataLine> {
new DataLine("Ñåðèÿ 1", series1),
new DataLine("Ñåðèÿ 2", series2),
new DataLine("Ñåðèÿ 3", series3),
};
DocumentDiagram diagram = new(fileUrl, docHeader, diagramName, EnumAreaLegend.Right, dataList);
componentDiagram.AddDiagram(diagram);
MessageBox.Show("Ñîõðàíåíî óñïåøíî", "Ðåçóëüòàò",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -0,0 +1,132 @@
<?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>
<metadata name="testComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="componentBigText.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>154, 17</value>
</metadata>
<metadata name="componentTable.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>308, 17</value>
</metadata>
<metadata name="componentDiagram.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>451, 17</value>
</metadata>
</root>

20
ComponentsView/Program.cs Normal file
View File

@ -0,0 +1,20 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace ComponentsView
{
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 FormComponents());
}
}
}