diff --git a/COPWinForms/COPWinForms.csproj b/COPWinForms/COPWinForms.csproj index b57c89e..976e1d7 100644 --- a/COPWinForms/COPWinForms.csproj +++ b/COPWinForms/COPWinForms.csproj @@ -8,4 +8,9 @@ enable + + + + + \ No newline at end of file diff --git a/COPWinForms/ComponentWord1.Designer.cs b/COPWinForms/ComponentWord1.Designer.cs new file mode 100644 index 0000000..45d6eb8 --- /dev/null +++ b/COPWinForms/ComponentWord1.Designer.cs @@ -0,0 +1,36 @@ +namespace COPWinForms +{ + partial class ComponentWord1 + { + /// + /// Обязательная переменная конструктора. + /// + 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/COPWinForms/ComponentWord1.cs b/COPWinForms/ComponentWord1.cs new file mode 100644 index 0000000..4824cc9 --- /dev/null +++ b/COPWinForms/ComponentWord1.cs @@ -0,0 +1,88 @@ +using Aspose.Words; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace COPWinForms +{ + public partial class ComponentWord1 : Component + { + private string _fileName; + + // private WordprocessingDocument? _wordDocument; + + // private Body? _docBody; + + public string FileName + { + set + { + if (string.IsNullOrEmpty(value)) + { + return; + } + if (!value.EndsWith(".docx")) + { + throw new ArgumentException("No docx file"); + } + _fileName = value; + } + } + public ComponentWord1() + { + InitializeComponent(); + _fileName = string.Empty; + } + public ComponentWord1(IContainer container) + { + container.Add(this); + InitializeComponent(); + _fileName = string.Empty; + } + public void CreateWordText(TextWord textWord) + { + // Создание документа + 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(textWord.DocumentTitle); + + // Создание обычного стиля для остального текста + Style normalStyle = builder.Document.Styles[StyleIdentifier.Normal]; + normalStyle.Font.Size = 12; + + // Применение обычного стиля для остального текста + builder.ParagraphFormat.Style = normalStyle; + + // Установка заголовка документа + document.BuiltInDocumentProperties.Title = textWord.DocumentTitle; + + foreach (string textLine in textWord.TextData) + { + // Добавление строки текста в документ + builder.Writeln(textLine); + } + document.Save(textWord.FilePath); + } + + bool CheckData(string[] data) + { + for (int i = 0; i < data.Length; i++) + { + if (string.IsNullOrEmpty(data[i])) return false; + } + + return true; + } + + } +} diff --git a/COPWinForms/ComponentWord2.Designer.cs b/COPWinForms/ComponentWord2.Designer.cs new file mode 100644 index 0000000..af0c2b4 --- /dev/null +++ b/COPWinForms/ComponentWord2.Designer.cs @@ -0,0 +1,36 @@ +namespace COPWinForms +{ + partial class ComponentWord2 + { + /// + /// Обязательная переменная конструктора. + /// + 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/COPWinForms/ComponentWord2.cs b/COPWinForms/ComponentWord2.cs new file mode 100644 index 0000000..c6d353e --- /dev/null +++ b/COPWinForms/ComponentWord2.cs @@ -0,0 +1,101 @@ +using Aspose.Words.Drawing.Charts; +using Aspose.Words; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Aspose.Words.Tables; + +namespace COPWinForms +{ + public partial class ComponentWord2 : Component + { + public ComponentWord2() + { + InitializeComponent(); + } + + public ComponentWord2(IContainer container) + { + container.Add(this); + + InitializeComponent(); + } + + public void CreateTable(string filePath, string documentTitle, List columnDefinitions, List data) + { + // Проверка наличия данных и определений столбцов + if (data == null) + { + throw new ArgumentException("Data or column definitions are null or empty"); + } + + // Проверка, что все ячейки шапки заполнены и для каждого столбца определено свойство/поле класса + foreach (var columnDefinition in columnDefinitions) + { + if (string.IsNullOrEmpty(columnDefinition.Header) || string.IsNullOrEmpty(columnDefinition.PropertyName)) + { + throw new ArgumentException($"Incomplete column definition: {columnDefinition.Header}"); + } + } + + // Создание документа + 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(documentTitle); + + // Создание таблицы + Table table = builder.StartTable(); + + // Вставка шапки таблицы + foreach (var columnDefinition in columnDefinitions) + { + builder.InsertCell(); + builder.Write(columnDefinition.Header); + } + builder.EndRow(); + + // Вставка данных в таблицу + foreach (var item in data) + { + + foreach (var columnDefinition in columnDefinitions) + { + builder.InsertCell(); + // Получение значения свойства/поля объекта по заданному имени + var propertyValue = item.GetType() + .GetProperty(columnDefinition.PropertyName)? + .GetValue(item)?.ToString(); + + // Вставка значения в ячейку + builder.Write(propertyValue ?? ""); + + } + + builder.EndRow(); + } + + builder.EndTable(); + + // Сохранение документа в файл + document.Save(filePath); + } + + public class ColumnDefinition + { + public string Header { get; set; } + public string PropertyName { get; set; } + } + } + +} diff --git a/COPWinForms/ComponentWord3.Designer.cs b/COPWinForms/ComponentWord3.Designer.cs new file mode 100644 index 0000000..4b5096d --- /dev/null +++ b/COPWinForms/ComponentWord3.Designer.cs @@ -0,0 +1,36 @@ +namespace COPWinForms +{ + partial class ComponentWord3 + { + /// + /// Обязательная переменная конструктора. + /// + 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/COPWinForms/ComponentWord3.cs b/COPWinForms/ComponentWord3.cs new file mode 100644 index 0000000..1cc5272 --- /dev/null +++ b/COPWinForms/ComponentWord3.cs @@ -0,0 +1,77 @@ +using Aspose.Words.Drawing.Charts; +using Aspose.Words; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using Aspose.Words.Drawing; + +namespace COPWinForms +{ + public partial class ComponentWord3 : Component + { + private string _fileName; + public string FileName + { + set + { + if (string.IsNullOrEmpty(value)) + { + return; + } + if (!value.EndsWith(".docx")) + { + throw new ArgumentException("No docx file"); + } + _fileName = value; + } + } + + public ComponentWord3() + { + InitializeComponent(); + } + + public ComponentWord3(IContainer container) + { + container.Add(this); + + InitializeComponent(); + } + + public void CreateLineChart(string filePath, string documentTitle, string chartTitle, string[] categories, string[] seriesName, double[][] data, LegendPosition legendPosition) + { + // Создание документа + Document document = new Document(); + DocumentBuilder builder = new DocumentBuilder(document); + + document.BuiltInDocumentProperties.Title = documentTitle; + + // Вставка диаграммы + Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300); + Chart chart = chartShape.Chart; + + // Настройка заголовка диаграммы + ChartTitle title = chart.Title; + title.Text = chartTitle; + + ChartSeriesCollection seriesColl = chart.Series; + seriesColl.Clear(); // Очищаем существующие серии перед добавлением новых + + // Добавление данных в диаграмму + for (int i = 0; i < seriesName.Length; i++) + { + seriesColl.Add(seriesName[i], categories, data[i]); + } + + chart.Legend.Position = (Aspose.Words.Drawing.Charts.LegendPosition)legendPosition; + + // Сохранение документа в файл + document.Save(filePath); + } + + + //СДЕЛАТЬ ПРОВЕРКУ!!!!!! + + } +} diff --git a/COPWinForms/LegendPosition.cs b/COPWinForms/LegendPosition.cs new file mode 100644 index 0000000..a7f8624 --- /dev/null +++ b/COPWinForms/LegendPosition.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace COPWinForms +{ + public enum LegendPosition + { + Top, + Bottom, + Left, + Right + } +} diff --git a/COPWinForms/TextWord.cs b/COPWinForms/TextWord.cs new file mode 100644 index 0000000..8337071 --- /dev/null +++ b/COPWinForms/TextWord.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace COPWinForms +{ + public class TextWord + { + public string FilePath = string.Empty; + + public string DocumentTitle = string.Empty; + + public string[] TextData; + + public TextWord(string filePath, string documentTitle, string[] textData) + { + FilePath = filePath; + DocumentTitle = documentTitle; + TextData = textData; + } + } +} diff --git a/COP_1/COP_1.sln b/COP_1/COP_1.sln index 63986ab..6b37ea8 100644 --- a/COP_1/COP_1.sln +++ b/COP_1/COP_1.sln @@ -3,11 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.3.32825.248 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "COP_1", "COP_1.csproj", "{3A354E62-6788-412B-8F8F-5A3484373BDA}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "COPWinForms", "..\COPWinForms\COPWinForms.csproj", "{C88D51BC-B17E-40DD-BC69-480DD08ED488}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinFormsTest", "..\WinFormsTest\WinFormsTest.csproj", "{75E77B58-7C69-4C52-8283-03EBC03D2C85}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinFormsTest", "..\WinFormsTest\WinFormsTest.csproj", "{75E77B58-7C69-4C52-8283-03EBC03D2C85}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,10 +13,6 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {3A354E62-6788-412B-8F8F-5A3484373BDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3A354E62-6788-412B-8F8F-5A3484373BDA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3A354E62-6788-412B-8F8F-5A3484373BDA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3A354E62-6788-412B-8F8F-5A3484373BDA}.Release|Any CPU.Build.0 = Release|Any CPU {C88D51BC-B17E-40DD-BC69-480DD08ED488}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C88D51BC-B17E-40DD-BC69-480DD08ED488}.Debug|Any CPU.Build.0 = Debug|Any CPU {C88D51BC-B17E-40DD-BC69-480DD08ED488}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/WinFormsTest/FormTestApp.Designer.cs b/WinFormsTest/FormTestApp.Designer.cs index 74c7af7..907dcad 100644 --- a/WinFormsTest/FormTestApp.Designer.cs +++ b/WinFormsTest/FormTestApp.Designer.cs @@ -28,6 +28,7 @@ /// private void InitializeComponent() { + this.components = new System.ComponentModel.Container(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); @@ -41,6 +42,12 @@ this.componentlBox1 = new COPWinForms.ComponentLBox(); this.textBoxShowItem = new System.Windows.Forms.TextBox(); this.componentcBox1 = new COPWinForms.ComponentCBox(); + this.componentWord11 = new COPWinForms.ComponentWord1(this.components); + this.buttonSave1 = new System.Windows.Forms.Button(); + this.componentWord31 = new COPWinForms.ComponentWord3(this.components); + this.button2 = new System.Windows.Forms.Button(); + this.componentWord21 = new COPWinForms.ComponentWord2(this.components); + this.button3 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 @@ -131,6 +138,7 @@ this.componenttBox1.Pattern = null; this.componenttBox1.Size = new System.Drawing.Size(188, 46); this.componenttBox1.TabIndex = 16; + this.componenttBox1.TextBoxValue = null; // // componentlBox1 // @@ -156,11 +164,44 @@ this.componentcBox1.TabIndex = 19; this.componentcBox1.CursorChanged += new System.EventHandler(this.componentcBox1_ExplicitEvent); // + // buttonSave1 + // + this.buttonSave1.Location = new System.Drawing.Point(161, 307); + this.buttonSave1.Name = "buttonSave1"; + this.buttonSave1.Size = new System.Drawing.Size(147, 29); + this.buttonSave1.TabIndex = 20; + this.buttonSave1.Text = "Сохранить 1"; + this.buttonSave1.UseVisualStyleBackColor = true; + this.buttonSave1.Click += new System.EventHandler(this.buttonSave1_Click); + // + // button2 + // + this.button2.Location = new System.Drawing.Point(603, 307); + this.button2.Name = "button2"; + this.button2.Size = new System.Drawing.Size(147, 29); + this.button2.TabIndex = 21; + this.button2.Text = "Сохранить 3"; + this.button2.UseVisualStyleBackColor = true; + this.button2.Click += new System.EventHandler(this.button2_Click); + // + // button3 + // + this.button3.Location = new System.Drawing.Point(385, 307); + this.button3.Name = "button3"; + this.button3.Size = new System.Drawing.Size(147, 29); + this.button3.TabIndex = 22; + this.button3.Text = "Сохранить 2"; + this.button3.UseVisualStyleBackColor = true; + this.button3.Click += new System.EventHandler(this.button3_Click); + // // FormTestApp // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1027, 288); + this.ClientSize = new System.Drawing.Size(1027, 384); + this.Controls.Add(this.button3); + this.Controls.Add(this.button2); + this.Controls.Add(this.buttonSave1); this.Controls.Add(this.componentcBox1); this.Controls.Add(this.textBoxShowItem); this.Controls.Add(this.componentlBox1); @@ -193,6 +234,12 @@ private COPWinForms.ComponentLBox componentlBox1; private TextBox textBoxShowItem; private COPWinForms.ComponentCBox componentcBox1; + private COPWinForms.ComponentWord1 componentWord11; + private Button buttonSave1; + private COPWinForms.ComponentWord3 componentWord31; + private Button button2; + private COPWinForms.ComponentWord2 componentWord21; + private Button button3; } #endregion diff --git a/WinFormsTest/FormTestApp.cs b/WinFormsTest/FormTestApp.cs index 175fdc4..479b59c 100644 --- a/WinFormsTest/FormTestApp.cs +++ b/WinFormsTest/FormTestApp.cs @@ -1,6 +1,8 @@ using COPWinForms; using System.Collections.Generic; +using System.ComponentModel; using System.Windows.Forms; +using static COPWinForms.ComponentWord2; namespace WinFormsTest { @@ -8,6 +10,9 @@ namespace WinFormsTest { List list = new List(); List students = new List(); + List listToSave = new List(); + string[] testArray = { " , \r\n ( ),\r\n ( ) \r\n( \r\n ). \r\n - . \r\n .", " " }; + public FormTestApp() { list = new List(); @@ -31,6 +36,10 @@ namespace WinFormsTest componentcBox1.ExplicitEvent += Event_Handler; componenttBox1.ExplicitEvent += Event_Handler; componenttBox1.setExample("eeee@mail.ru"); + + + + componentWord11.FileName = "E:\\1.docx"; } private void buttonAdd_Click(object sender, EventArgs e) @@ -76,8 +85,6 @@ namespace WinFormsTest { MessageBox.Show(ex.Message); } - - } private void button1_Click(object sender, EventArgs e) @@ -94,5 +101,95 @@ namespace WinFormsTest { MessageBox.Show("Change avatar"); } + + private void buttonSave1_Click(object sender, EventArgs e) + { + // + using var dialog = new SaveFileDialog + { + Filter = "docx|*.docx" + }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + TextWord textWord = new(dialog.FileName, " 1", testArray); + componentWord11.CreateWordText(textWord); + + MessageBox.Show("", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + } + + private void button2_Click(object sender, EventArgs e) + { + ComponentWord3 chartComponent = new ComponentWord3(); + string[] categories = new string[] { "Category1", "Category2", "Category3" }; + string[] seriesName = new string[] { "Series1", "Series2" }; + double[][] data = new double[][] + { + new double[] { 10, 20, 30 }, + new double[] { 15, 25, 35 } + }; + // + using var dialog = new SaveFileDialog + { + Filter = "docx|*.docx" + }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + componentWord31.CreateLineChart(dialog.FileName, " 3", " ", categories, seriesName, data, LegendPosition.Right); + MessageBox.Show(" ", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + } + + private void button3_Click(object sender, EventArgs e) + { + ComponentWord2 tableComponent = new ComponentWord2(); + List columnDefinitions = new List + { + new ColumnDefinition { Header = "FIO", PropertyName = "FIO" }, + new ColumnDefinition { Header = "Group", PropertyName = "Group" }, + new ColumnDefinition { Header = "Email", PropertyName = "Email" } + }; + + List data = new List + { + new Student { FIO = "John", Group = "ff", Email = "New York" }, + new Student { FIO = "Jane", Group = "kkk", Email = "London" }, + new Student { FIO = "Mike", Group = "jjj", Email = "Paris" } + }; + + // + using var dialog = new SaveFileDialog + { + Filter = "docx|*.docx" + }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + componentWord21.CreateTable(dialog.FileName, " 2", columnDefinitions, data); + MessageBox.Show(" ", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } \ No newline at end of file diff --git a/WinFormsTest/FormTestApp.resx b/WinFormsTest/FormTestApp.resx index f298a7b..f891814 100644 --- a/WinFormsTest/FormTestApp.resx +++ b/WinFormsTest/FormTestApp.resx @@ -57,4 +57,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 203, 17 + + + 389, 17 + \ No newline at end of file