From ee5ec2e1a5ad4c6f443d5a93201448319318eb07 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Fri, 6 Sep 2024 04:27:34 +0400 Subject: [PATCH] LabWork02 WiP --- Components/Components/Components.csproj | 5 + .../BigTextComponent.Designer.cs | 36 ++++ .../NonVisualComponents/BigTextComponent.cs | 81 +++++++ .../DiagramComponent.Designer.cs | 36 ++++ .../NonVisualComponents/DiagramComponent.cs | 140 +++++++++++++ .../HelperModels/LegendPosition.cs | 22 ++ .../HelperModels/LineChartConfig.cs | 41 ++++ .../HelperModels/MergeCells.cs | 35 ++++ .../TableComponent.Designer.cs | 36 ++++ .../NonVisualComponents/TableComponent.cs | 198 ++++++++++++++++++ Components/WinForms/Employee.cs | 96 +++++++++ .../FormNonVisualComponents.Designer.cs | 92 ++++++++ .../WinForms/FormNonVisualComponents.cs | 124 +++++++++++ .../WinForms/FormNonVisualComponents.resx | 129 ++++++++++++ ...er.cs => FormVisualComponents.Designer.cs} | 8 +- ...mComponents.cs => FormVisualComponents.cs} | 8 +- ...ponents.resx => FormVisualComponents.resx} | 0 Components/WinForms/Program.cs | 2 +- 18 files changed, 1080 insertions(+), 9 deletions(-) create mode 100644 Components/Components/NonVisualComponents/BigTextComponent.Designer.cs create mode 100644 Components/Components/NonVisualComponents/BigTextComponent.cs create mode 100644 Components/Components/NonVisualComponents/DiagramComponent.Designer.cs create mode 100644 Components/Components/NonVisualComponents/DiagramComponent.cs create mode 100644 Components/Components/NonVisualComponents/HelperModels/LegendPosition.cs create mode 100644 Components/Components/NonVisualComponents/HelperModels/LineChartConfig.cs create mode 100644 Components/Components/NonVisualComponents/HelperModels/MergeCells.cs create mode 100644 Components/Components/NonVisualComponents/TableComponent.Designer.cs create mode 100644 Components/Components/NonVisualComponents/TableComponent.cs create mode 100644 Components/WinForms/Employee.cs create mode 100644 Components/WinForms/FormNonVisualComponents.Designer.cs create mode 100644 Components/WinForms/FormNonVisualComponents.cs create mode 100644 Components/WinForms/FormNonVisualComponents.resx rename Components/WinForms/{FormComponents.Designer.cs => FormVisualComponents.Designer.cs} (98%) rename Components/WinForms/{FormComponents.cs => FormVisualComponents.cs} (95%) rename Components/WinForms/{FormComponents.resx => FormVisualComponents.resx} (100%) diff --git a/Components/Components/Components.csproj b/Components/Components/Components.csproj index 060aa1c..096def8 100644 --- a/Components/Components/Components.csproj +++ b/Components/Components/Components.csproj @@ -7,4 +7,9 @@ enable + + + + + diff --git a/Components/Components/NonVisualComponents/BigTextComponent.Designer.cs b/Components/Components/NonVisualComponents/BigTextComponent.Designer.cs new file mode 100644 index 0000000..cc20a18 --- /dev/null +++ b/Components/Components/NonVisualComponents/BigTextComponent.Designer.cs @@ -0,0 +1,36 @@ +namespace Components.NonVisualComponents +{ + partial class BigTextComponent + { + /// + /// Обязательная переменная конструктора. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + } + + #endregion + } +} diff --git a/Components/Components/NonVisualComponents/BigTextComponent.cs b/Components/Components/NonVisualComponents/BigTextComponent.cs new file mode 100644 index 0000000..dc36804 --- /dev/null +++ b/Components/Components/NonVisualComponents/BigTextComponent.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using Excel = Microsoft.Office.Interop.Excel; + +namespace Components.NonVisualComponents +{ + /// + /// Не визуальный компонент для создания документа Excel с большим текстом + /// + public partial class BigTextComponent : Component + { + /// + /// Конструктор + /// + public BigTextComponent() + { + InitializeComponent(); + } + + /// + /// Конструктор + /// + /// + public BigTextComponent(IContainer container) + { + container.Add(this); + + InitializeComponent(); + } + + /// + /// Создать документ + /// + /// + /// + /// + /// + public void CreateDocument(string filepath, string title, string[] rows) + { + if (string.IsNullOrEmpty(filepath)) + { + throw new ArgumentNullException("Не указан путь к файлу!"); + } + if (string.IsNullOrEmpty(title)) + { + throw new ArgumentNullException("Не указан заголовок документа!"); + } + if (rows == null || rows.Length == 0) + { + throw new ArgumentNullException("Массив с текстом не заполнен!"); + } + + Excel.Application excelApp = new Excel.Application(); + Excel.Workbook workbook = excelApp.Workbooks.Add(); + Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1]; + + worksheet.Cells[1, 1] = title; + for (int index = 0; index < rows.Length; index++) + { + worksheet.Cells[index + 3, 1] = rows[index]; + } + + if (File.Exists(filepath)) + { + File.Delete(filepath); + } + + excelApp.Application.ActiveWorkbook.SaveAs(filepath); + workbook.Close(true); + excelApp.Quit(); + + Marshal.ReleaseComObject(excelApp); + } + } +} diff --git a/Components/Components/NonVisualComponents/DiagramComponent.Designer.cs b/Components/Components/NonVisualComponents/DiagramComponent.Designer.cs new file mode 100644 index 0000000..321dee9 --- /dev/null +++ b/Components/Components/NonVisualComponents/DiagramComponent.Designer.cs @@ -0,0 +1,36 @@ +namespace Components.NonVisualComponents +{ + partial class DiagramComponent + { + /// + /// Обязательная переменная конструктора. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + } + + #endregion + } +} diff --git a/Components/Components/NonVisualComponents/DiagramComponent.cs b/Components/Components/NonVisualComponents/DiagramComponent.cs new file mode 100644 index 0000000..ea6e257 --- /dev/null +++ b/Components/Components/NonVisualComponents/DiagramComponent.cs @@ -0,0 +1,140 @@ +using Components.NonVisualComponents.HelperModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using Excel = Microsoft.Office.Interop.Excel; + +namespace Components.NonVisualComponents +{ + /// + /// Не визуальный компонент для создания документа Excel с линейной диаграммой + /// + public partial class DiagramComponent : Component + { + /// + /// Конструктор + /// + public DiagramComponent() + { + InitializeComponent(); + } + + /// + /// Конструктор + /// + /// + public DiagramComponent(IContainer container) + { + container.Add(this); + + InitializeComponent(); + } + + /// + /// Создать документ + /// + /// + /// + public void CreateDocument(LineChartConfig config) + { + if (config == null) + { + throw new ArgumentNullException("Не задана конфигурация для построения линйеной диаграммы!"); + } + if (string.IsNullOrEmpty(config.Filepath)) + { + throw new ArgumentNullException("Не указан путь к файлу!"); + } + if (string.IsNullOrEmpty(config.Header)) + { + throw new ArgumentNullException("Не указан заголовок документа!"); + } + if (string.IsNullOrEmpty(config.ChartTitle)) + { + throw new ArgumentNullException("Не указано название диаграммы!"); + } + if (config.Values == null || config.Values.Count == 0) + { + throw new ArgumentNullException("Не заданы значения для отображения на диаграмме!"); + } + + Excel.Application excelApp = new Excel.Application(); + Excel.Workbook workbook = excelApp.Workbooks.Add(); + Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1]; + + worksheet.Cells[1, 1] = config.Header; + + // Создание диаграммы + Excel.ChartObjects chartObjs = (Excel.ChartObjects)worksheet.ChartObjects(); + Excel.ChartObject chartObj = chartObjs.Add(5, 50, 300, 300); + Excel.Chart excelChart = chartObj.Chart; + excelChart.ChartType = Excel.XlChartType.xlLine; + + // Запись данных + Excel.Range[] valuesRange = new Excel.Range[config.Values.Count]; + int leftTopI = 2, leftTopJ = 1; + for (int i = 0; i < config.Values.Count; i++) + { + string key = config.Values.Keys.ToList()[i]; + for (int j = 0; j < config.Values[key].Count; j++) + { + worksheet.Cells[leftTopI + i, leftTopJ + j] = config.Values[key][j]; + } + + valuesRange[i] = worksheet.Range + [worksheet.Cells[leftTopI + i, leftTopJ], + worksheet.Cells[leftTopI + i, leftTopJ + config.Values[key].Count - 1]]; + } + + // Задание данных + Excel.SeriesCollection seriesCollection = (Excel.SeriesCollection)excelChart.SeriesCollection(); + for (int i = 0; i < config.Values.Keys.Count; i++) + { + Excel.Series series = seriesCollection.NewSeries(); + series.Name = config.Values.Keys.ToList()[i]; + series.Values = valuesRange[i]; + } + + // Задание заголовка + excelChart.HasTitle = true; + excelChart.ChartTitle.Text = config.ChartTitle; + + // Задание легенды + excelChart.HasLegend = true; + switch (config.LegendPosition) + { + case LegendPosition.Top: + excelChart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionTop; + break; + case LegendPosition.Right: + excelChart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionRight; + break; + case LegendPosition.Bottom: + excelChart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionBottom; + break; + case LegendPosition.Left: + excelChart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionLeft; + break; + default: + excelChart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionBottom; + break; + } + + if (File.Exists(config.Filepath)) + { + File.Delete(config.Filepath); + } + + excelApp.Application.ActiveWorkbook.SaveAs(config.Filepath); + workbook.Close(true); + excelApp.Quit(); + + Marshal.ReleaseComObject(excelApp); + } + } +} diff --git a/Components/Components/NonVisualComponents/HelperModels/LegendPosition.cs b/Components/Components/NonVisualComponents/HelperModels/LegendPosition.cs new file mode 100644 index 0000000..5a9dff6 --- /dev/null +++ b/Components/Components/NonVisualComponents/HelperModels/LegendPosition.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Components.NonVisualComponents.HelperModels +{ + /// + /// Положение легенды на графике + /// + public enum LegendPosition + { + Top, + + Right, + + Bottom, + + Left, + } +} diff --git a/Components/Components/NonVisualComponents/HelperModels/LineChartConfig.cs b/Components/Components/NonVisualComponents/HelperModels/LineChartConfig.cs new file mode 100644 index 0000000..e566ff1 --- /dev/null +++ b/Components/Components/NonVisualComponents/HelperModels/LineChartConfig.cs @@ -0,0 +1,41 @@ +using Microsoft.Office.Interop.Excel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Components.NonVisualComponents.HelperModels +{ + /// + /// Вспомогательный класс конфигурации для построения линейной диаграммы + /// + public class LineChartConfig + { + /// + /// Путь к файлу + /// + public string Filepath { get; set; } = string.Empty; + + /// + /// Заголовок + /// + public string Header { get; set; } = string.Empty; + + /// + /// Название диаграммы + /// + public string ChartTitle { get; set; } = string.Empty; + + /// + /// Значения для отображения на диаграмме + /// + public Dictionary> Values { get; set; } = new(); + + /// + /// Положение легенды на диаграмме + /// + public LegendPosition LegendPosition { get; set; } + } + +} diff --git a/Components/Components/NonVisualComponents/HelperModels/MergeCells.cs b/Components/Components/NonVisualComponents/HelperModels/MergeCells.cs new file mode 100644 index 0000000..db10e9f --- /dev/null +++ b/Components/Components/NonVisualComponents/HelperModels/MergeCells.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Components.NonVisualComponents.HelperModels +{ + /// + /// Вспомогательный класс для объединения ячеек в Excel + /// + public class MergeCells + { + /// + /// Заголовок + /// + public string Header; + + /// + /// Индексы ячеек + /// + public int[] CellIndexes; + + /// + /// Конструктор + /// + /// + /// + public MergeCells(string header, int[] cellIndexes) + { + Header = header; + CellIndexes = cellIndexes; + } + } +} diff --git a/Components/Components/NonVisualComponents/TableComponent.Designer.cs b/Components/Components/NonVisualComponents/TableComponent.Designer.cs new file mode 100644 index 0000000..6e3e6f8 --- /dev/null +++ b/Components/Components/NonVisualComponents/TableComponent.Designer.cs @@ -0,0 +1,36 @@ +namespace Components.NonVisualComponents +{ + partial class TableComponent + { + /// + /// Обязательная переменная конструктора. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + } + + #endregion + } +} diff --git a/Components/Components/NonVisualComponents/TableComponent.cs b/Components/Components/NonVisualComponents/TableComponent.cs new file mode 100644 index 0000000..49da32b --- /dev/null +++ b/Components/Components/NonVisualComponents/TableComponent.cs @@ -0,0 +1,198 @@ +using Components.NonVisualComponents.HelperModels; +using Microsoft.Office.Interop.Excel; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using Excel = Microsoft.Office.Interop.Excel; + +namespace Components.NonVisualComponents +{ + /// + /// Не визуальный компонент для создания документа Excel с настраиваемой таблицей + /// + public partial class TableComponent : Component + { + private char[] _columnIndexes = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; + + /// + /// Конструктор + /// + public TableComponent() + { + InitializeComponent(); + } + + /// + /// Конструктор + /// + /// + public TableComponent(IContainer container) + { + container.Add(this); + + InitializeComponent(); + } + + /// + /// Создать документ + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void CreateDocument(string filepath, string title, + List mergeCells, List columnsWidth, + List columns, List headers, + List data) where T : class, new() + { + if (string.IsNullOrEmpty(filepath)) + { + throw new ArgumentNullException("Не указан путь к файлу!"); + } + if (string.IsNullOrEmpty(title)) + { + throw new ArgumentNullException("Не указан заголовок документа!"); + } + if (mergeCells == null || mergeCells.Count == 0 || columnsWidth == null || columnsWidth.Count == 0) + { + throw new ArgumentNullException("Не заполнена информация по колонкам!"); + } + if (columns == null || columns.Count == 0 || headers == null || headers.Count == 0 || columns.Count != headers.Count) + { + throw new ArgumentNullException("Не заполнена информация по заголовкам!"); + } + if (columnsWidth.Count != columns.Count) + { + throw new Exception("Количество заголовков не соответствует количеству размеров столбцов!"); + } + if (data == null) + { + throw new ArgumentNullException("Данные не заполнены!"); + } + + Excel.Application excelApp = new Excel.Application(); + Excel.Workbook workbook = excelApp.Workbooks.Add(); + Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1]; + + worksheet.Cells[1, 1] = title; + + // Заголовки таблицы + for (int i = 1; i <= headers.Count; i++) + { + if (string.IsNullOrEmpty(headers[i - 1])) + { + throw new Exception("Заголовок не имеет данных!"); + } + + worksheet.Cells[2, i] = headers[i - 1]; + + Excel.Range column = (Excel.Range)worksheet.Columns[i]; + //column.ColumnWidth = columnsWidth[i - 1]; + + Excel.Range cell = (Excel.Range)worksheet.Cells[2, i]; + cell.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; + cell.VerticalAlignment = Excel.XlHAlign.xlHAlignGeneral; + cell.Font.Bold = true; + } + + // Объединение ячеек по столбцам + List mergeIndexes = new List(); + foreach (var merge in mergeCells) + { + mergeIndexes.AddRange(merge.CellIndexes); + + Excel.Range rangeToCopy = worksheet.get_Range($"{_columnIndexes[merge.CellIndexes[0]]}2", $"{_columnIndexes[merge.CellIndexes[merge.CellIndexes.Length - 1]]}2").Cells; + Excel.Range rangeToInsert = worksheet.get_Range($"{_columnIndexes[merge.CellIndexes[0]]}3", $"{_columnIndexes[merge.CellIndexes[merge.CellIndexes.Length - 1]]}3").Cells; + rangeToInsert.Insert(Excel.XlInsertShiftDirection.xlShiftToRight, rangeToCopy.Cut()); + + Excel.Range rangeMerge = worksheet.get_Range($"{_columnIndexes[merge.CellIndexes[0]]}2", $"{_columnIndexes[merge.CellIndexes[merge.CellIndexes.Length - 1]]}2").Cells; + rangeMerge.Merge(); + worksheet.Cells[2, merge.CellIndexes[0] + 1] = merge.Header; + Excel.Range cell = (Excel.Range)worksheet.Cells[2, merge.CellIndexes[0] + 1]; + cell.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; + cell.VerticalAlignment = Excel.XlHAlign.xlHAlignCenter; + cell.Font.Bold = true; + } + + // Объединение ячеек по строкам, которые не объединяются по столбцам + for (int i = 1; i <= headers.Count; i++) + { + if (!mergeIndexes.Contains(i - 1)) + { + Excel.Range range = worksheet.get_Range($"{_columnIndexes[i - 1]}2", $"{_columnIndexes[i - 1]}3").Cells; + range.Merge(); + } + } + + // Заполнение данных + int row = 4; + foreach (var item in data) + { + var properties = item.GetType().GetProperties(); + if (properties.Count() != columns.Count) + { + throw new Exception("Количество полей объекта не соответствует количеству столбцов в таблице!"); + } + + for (int i = 0; i < properties.Count(); i++) + { + int columnIndex = 0; + var property = properties[i]; + var propertyValue = property.GetValue(item); + if (propertyValue == null) + { + throw new Exception("Поле имеет пустое значение!"); + } + + foreach (var column in columns) + { + if (column == property.Name) + { + columnIndex = columns.IndexOf(column) + 1; + break; + } + } + + if (columnIndex != 0) + { + worksheet.Cells[i, columnIndex] = propertyValue; + } + } + + row++; + } + + // Границы таблицы + for (int i = 2; i <= (data.Count() + 3); i++) + { + for (int j = 1; j <= headers.Count(); j++) + { + Excel.Range cell = (Excel.Range)worksheet.Cells[i, j]; + cell.BorderAround(true); + } + } + + if (File.Exists(filepath)) + { + File.Delete(filepath); + } + + excelApp.Application.ActiveWorkbook.SaveAs(filepath); + workbook.Close(true); + excelApp.Quit(); + + Marshal.ReleaseComObject(excelApp); + } + } +} diff --git a/Components/WinForms/Employee.cs b/Components/WinForms/Employee.cs new file mode 100644 index 0000000..21d6c31 --- /dev/null +++ b/Components/WinForms/Employee.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WinForms +{ + /// + /// Сущность "Человек" + /// + public class Employee + { + /// + /// Идентификатор + /// + public int Id { get; set; } + + /// + /// Статус + /// + public string Status { get; set; } + + /// + /// Имя + /// + public string Name { get; set; } + + /// + /// Фамилия + /// + public string Surname { get; set; } + + /// + /// Возраст + /// + public int Age { get; set; } + + /// + /// Наличие детей + /// + public string Kids { get; set; } + + /// + /// Наличие личного автомобиля + /// + public string Car { get; set; } + + /// + /// Подразделение + /// + public string Department { get; set; } + + /// + /// Должность + /// + public string Post { get; set; } + + /// + /// Премия + /// + public double Prize { get; set; } + + /// + /// Конструктор по умолчанию + /// + public Employee() { } + + /// + /// Конструктор с параметрами + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public Employee(int id, string status, string name, string surname, int age, string kids, string car, string department, string post, double prize) + { + Id = id; + Status = status; + Name = name; + Surname = surname; + Age = age; + Kids = kids; + Car = car; + Department = department; + Post = post; + Prize = prize; + } + } +} diff --git a/Components/WinForms/FormNonVisualComponents.Designer.cs b/Components/WinForms/FormNonVisualComponents.Designer.cs new file mode 100644 index 0000000..b153344 --- /dev/null +++ b/Components/WinForms/FormNonVisualComponents.Designer.cs @@ -0,0 +1,92 @@ +namespace WinForms +{ + partial class FormNonVisualComponents + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + buttonCreateTextDocument = new Button(); + buttonCreateTableDocument = new Button(); + buttonCreateDiagramDocument = new Button(); + bigTextComponent1 = new Components.NonVisualComponents.BigTextComponent(components); + tableComponent1 = new Components.NonVisualComponents.TableComponent(components); + diagramComponent1 = new Components.NonVisualComponents.DiagramComponent(components); + SuspendLayout(); + // + // buttonCreateTextDocument + // + buttonCreateTextDocument.Location = new Point(12, 30); + buttonCreateTextDocument.Name = "buttonCreateTextDocument"; + buttonCreateTextDocument.Size = new Size(125, 50); + buttonCreateTextDocument.TabIndex = 0; + buttonCreateTextDocument.Text = "Создать документ с текстом"; + buttonCreateTextDocument.UseVisualStyleBackColor = true; + buttonCreateTextDocument.Click += buttonCreateTextDocument_Click; + // + // buttonCreateTableDocument + // + buttonCreateTableDocument.Location = new Point(180, 30); + buttonCreateTableDocument.Name = "buttonCreateTableDocument"; + buttonCreateTableDocument.Size = new Size(125, 50); + buttonCreateTableDocument.TabIndex = 1; + buttonCreateTableDocument.Text = "Создать документ с таблицей"; + buttonCreateTableDocument.UseVisualStyleBackColor = true; + buttonCreateTableDocument.Click += buttonCreateTableDocument_Click; + // + // buttonCreateDiagramDocument + // + buttonCreateDiagramDocument.Location = new Point(347, 30); + buttonCreateDiagramDocument.Name = "buttonCreateDiagramDocument"; + buttonCreateDiagramDocument.Size = new Size(125, 50); + buttonCreateDiagramDocument.TabIndex = 2; + buttonCreateDiagramDocument.Text = "Создать документ с диаграммой"; + buttonCreateDiagramDocument.UseVisualStyleBackColor = true; + buttonCreateDiagramDocument.Click += buttonCreateDiagramDocument_Click; + // + // FormNonVisualComponents + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(484, 111); + Controls.Add(buttonCreateDiagramDocument); + Controls.Add(buttonCreateTableDocument); + Controls.Add(buttonCreateTextDocument); + Name = "FormNonVisualComponents"; + Text = "Не визуальные компоненты"; + ResumeLayout(false); + } + + #endregion + + private Button buttonCreateTextDocument; + private Button buttonCreateTableDocument; + private Button buttonCreateDiagramDocument; + private Components.NonVisualComponents.BigTextComponent bigTextComponent1; + private Components.NonVisualComponents.TableComponent tableComponent1; + private Components.NonVisualComponents.DiagramComponent diagramComponent1; + } +} \ No newline at end of file diff --git a/Components/WinForms/FormNonVisualComponents.cs b/Components/WinForms/FormNonVisualComponents.cs new file mode 100644 index 0000000..bf49050 --- /dev/null +++ b/Components/WinForms/FormNonVisualComponents.cs @@ -0,0 +1,124 @@ +using Components.NonVisualComponents; +using Components.NonVisualComponents.HelperModels; +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 WinForms +{ + /// + /// Форма для не визуальных компонентов + /// + public partial class FormNonVisualComponents : Form + { + /// + /// Конструктор + /// + public FormNonVisualComponents() + { + InitializeComponent(); + } + + /// + /// Создать документ с текстом + /// + /// + /// + private void buttonCreateTextDocument_Click(object sender, EventArgs e) + { + string filepath = "C:\\Users\\masen\\OneDrive\\Рабочий стол\\BigTextDocumentExcel.xls"; + string title = "Документ с большим текстом"; + + string[] rows = + { + "Съешь еще", + "этих мягких", + "французских булок", + "да выпей чаю" + }; + + bigTextComponent1.CreateDocument(filepath, title, rows); + } + + /// + /// Создать документ с таблицей + /// + /// + /// + private void buttonCreateTableDocument_Click(object sender, EventArgs e) + { + string filepath = "C:\\Users\\masen\\OneDrive\\Рабочий стол\\TableDocumentExcel.xls"; + string title = "Документ с таблицей"; + + List mergeCells = new List() + { + new MergeCells("Личные данные", new int[] { 2, 3, 4 }), + new MergeCells("Работа", new int[] { 7, 8 }) + }; + List columnsWidth = new List() + { + 20, 20, 30, 30, 30, 30, 30, 50, 50, 30 + }; + + List columns = new List() + { + "Id", "Status", "Name", "Surname", "Age", "Kids", "Car", "Department", "Post", "Prize" + }; + List headers = new List() + { + "Идент.", "Статус", "Имя", "Фамилия", "Возраст", "Дети", "Машина", "Подразделение", "Должность", "Премия" + }; + + List data = new List() + { + new Employee(1, "нет", "Иван", "Иванов", 34, "нет", "есть", "Департамент 1", "Инженер", 2000.1), + new Employee(2, "нет", "Петр", "Петров", 44, "есть", "есть", "Департамент 1", "Инженер", 2000.1), + new Employee(3, "да", "Сергей", "Сепгеев", 55, "нет", "есть", "Департамент 1", "Руководитель", 5000.5), + new Employee(4, "нет", "Ольга", "Иванва", 34, "есть", "нет", "Бухгалтерия", "Бухгалтер", 2000.1), + new Employee(5, "да", "Татьяна", "Петрова", 44, "нет", "нет", "Бухгалтерия", "Старший бухгалтер", 7000.6) + }; + + tableComponent1.CreateDocument(filepath, title, + mergeCells, columnsWidth, + columns, headers, + data); + } + + /// + /// Создать документ с диаграммой + /// + /// + /// + private void buttonCreateDiagramDocument_Click(object sender, EventArgs e) + { + LineChartConfig config = new LineChartConfig(); + config.Filepath = "C:\\Users\\masen\\OneDrive\\Рабочий стол\\DiagramDocumentExcel.xls"; + config.Header = "Документ с диаграммой"; + config.ChartTitle = "Моя диаграмма"; + string[] charts = { "График 1", "График 2" }; + + var data = new Dictionary>(); + for (int i = 0; i < 2; i++) + { + var row = new List(); + for (var j = 0; j < 5; j++) + { + row.Add(5 * i + j + 1); + } + + data.Add(charts[i], row); + } + config.Values = data; + + config.LegendPosition = LegendPosition.Bottom; + + diagramComponent1.CreateDocument(config); + } + } +} diff --git a/Components/WinForms/FormNonVisualComponents.resx b/Components/WinForms/FormNonVisualComponents.resx new file mode 100644 index 0000000..e613fef --- /dev/null +++ b/Components/WinForms/FormNonVisualComponents.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 179, 17 + + + 329, 17 + + \ No newline at end of file diff --git a/Components/WinForms/FormComponents.Designer.cs b/Components/WinForms/FormVisualComponents.Designer.cs similarity index 98% rename from Components/WinForms/FormComponents.Designer.cs rename to Components/WinForms/FormVisualComponents.Designer.cs index e7d62ac..dc5bac8 100644 --- a/Components/WinForms/FormComponents.Designer.cs +++ b/Components/WinForms/FormVisualComponents.Designer.cs @@ -1,6 +1,6 @@ namespace WinForms { - partial class FormComponents + partial class FormVisualComponents { /// /// Required designer variable. @@ -230,7 +230,7 @@ customListBox.Size = new Size(332, 369); customListBox.TabIndex = 0; // - // FormComponents + // FormVisualComponents // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; @@ -238,8 +238,8 @@ Controls.Add(groupBox3); Controls.Add(groupBox2); Controls.Add(groupBox1); - Name = "FormComponents"; - Text = "Компоненты"; + Name = "FormVisualComponents"; + Text = "Визуальные компоненты"; groupBox1.ResumeLayout(false); groupBox1.PerformLayout(); groupBox2.ResumeLayout(false); diff --git a/Components/WinForms/FormComponents.cs b/Components/WinForms/FormVisualComponents.cs similarity index 95% rename from Components/WinForms/FormComponents.cs rename to Components/WinForms/FormVisualComponents.cs index eea6e9a..74f5022 100644 --- a/Components/WinForms/FormComponents.cs +++ b/Components/WinForms/FormVisualComponents.cs @@ -1,14 +1,14 @@ namespace WinForms { /// - /// + /// /// - public partial class FormComponents : Form + public partial class FormVisualComponents : Form { /// /// /// - public FormComponents() + public FormVisualComponents() { InitializeComponent(); @@ -120,7 +120,7 @@ namespace WinForms /// private void buttonGetObject_Click(object sender, EventArgs e) { - Person person = customListBox.GetObject(); + Employee person = customListBox.GetObject(); if (person == null) { labelObjectInfo.Text = " "; diff --git a/Components/WinForms/FormComponents.resx b/Components/WinForms/FormVisualComponents.resx similarity index 100% rename from Components/WinForms/FormComponents.resx rename to Components/WinForms/FormVisualComponents.resx diff --git a/Components/WinForms/Program.cs b/Components/WinForms/Program.cs index dc33c23..62dccf2 100644 --- a/Components/WinForms/Program.cs +++ b/Components/WinForms/Program.cs @@ -11,7 +11,7 @@ namespace WinForms // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormComponents()); + Application.Run(new FormNonVisualComponents()); } } } \ No newline at end of file